
'''simple docstring'''




import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import ConditionalDetrImageProcessor







class    A_	(unittest.TestCase							):
							"""simple docstring"""




							def __init__(		self			:Tuple       ,							lowerCAmelCase__			:Optional[int]       ,							lowerCAmelCase__			:List[str]=7       ,							lowerCAmelCase__			:Optional[int]=3       ,							lowerCAmelCase__			:Optional[Any]=30       ,							lowerCAmelCase__			:List[Any]=400       ,							lowerCAmelCase__			:List[str]=True       ,							lowerCAmelCase__			:Tuple=None       ,							lowerCAmelCase__			:List[str]=True       ,							lowerCAmelCase__			:Optional[int]=[0.5, 0.5, 0.5]       ,							lowerCAmelCase__			:Any=[0.5, 0.5, 0.5]       ,							lowerCAmelCase__			:str=True       ,							lowerCAmelCase__			:Optional[Any]=1 / 255       ,							lowerCAmelCase__			:Union[str, Any]=True       ,							)				->  Dict:


										'''simple docstring'''




										snake_case_				:					List[str]   =       size if size is not None else {"shortest_edge": 18, "longest_edge": 1_333}
										snake_case_				:					int   =       parent
										snake_case_				:					List[Any]   =       batch_size
										snake_case_				:					int   =       num_channels
										snake_case_				:					List[str]   =       min_resolution
										snake_case_				:					Dict   =       max_resolution
										snake_case_				:					Any   =       do_resize
										snake_case_				:					Optional[Any]   =       size
										snake_case_				:					Any   =       do_normalize
										snake_case_				:					Tuple   =       image_mean
										snake_case_				:					Tuple   =       image_std
										snake_case_				:					int   =       do_rescale
										snake_case_				:					str   =       rescale_factor
										snake_case_				:					int   =       do_pad

							def 							_A	(		self			:Any				)				->  List[str]:


										'''simple docstring'''




										return {
										    "do_resize": self.do_resize,
										    "size": self.size,
										    "do_normalize": self.do_normalize,
										    "image_mean": self.image_mean,
										    "image_std": self.image_std,
										    "do_rescale": self.do_rescale,
										    "rescale_factor": self.rescale_factor,
										    "do_pad": self.do_pad,
										}






							def 							_A	(		self			:Optional[Any]       ,							lowerCAmelCase__			:Optional[int]       ,							lowerCAmelCase__			:Optional[Any]=False				)				->  str:


										'''simple docstring'''




										if not batched:
													snake_case_				:					Dict   =       image_inputs[0]
													if isinstance(UpperCAmelCase_       ,							Image.Image				):
																snake_case_,	snake_case_				:					Optional[Any]   =       image.size
													else:
																snake_case_,	snake_case_				:					List[str]   =       image.shape[1], image.shape[2]
													if w < h:
																snake_case_				:					Any   =       int(self.size["shortest_edge"] * h / w				)
																snake_case_				:					str   =       self.size["shortest_edge"]
													elif w > h:
																snake_case_				:					Any   =       self.size["shortest_edge"]
																snake_case_				:					int   =       int(self.size["shortest_edge"] * w / h				)
													else:
																snake_case_				:					Any   =       self.size["shortest_edge"]
																snake_case_				:					int   =       self.size["shortest_edge"]

										else:
													snake_case_				:					List[Any]   =       []
													for image in image_inputs:
																snake_case_,	snake_case_				:					List[str]   =       self.get_expected_values([image]				)
																expected_values.append((expected_height, expected_width)				)
													snake_case_				:					List[Any]   =       max(UpperCAmelCase_       ,							key=lambda lowerCAmelCase__				: item[0]				)[0]
													snake_case_				:					Optional[Any]   =       max(UpperCAmelCase_       ,							key=lambda lowerCAmelCase__				: item[1]				)[1]

										return expected_height, expected_width







@require_torch
@require_vision
class    A_	(__UpperCAmelCase						,					unittest.TestCase							):
							"""simple docstring"""




							a__   		=	ConditionalDetrImageProcessor if is_vision_available() else None

							def 							_A	(		self			:int				)				->  List[Any]:


										'''simple docstring'''




										snake_case_				:					Union[str, Any]   =       ConditionalDetrImageProcessingTester(self				)

							@property
							def 							_A	(		self			:List[str]				)				->  Optional[Any]:


										'''simple docstring'''




										return self.image_processor_tester.prepare_image_processor_dict()

							def 							_A	(		self			:Optional[int]				)				->  int:


										'''simple docstring'''




										snake_case_				:					List[Any]   =       self.image_processing_class(**self.image_processor_dict				)
										self.assertTrue(hasattr(UpperCAmelCase_       ,							"image_mean"				)				)
										self.assertTrue(hasattr(UpperCAmelCase_       ,							"image_std"				)				)
										self.assertTrue(hasattr(UpperCAmelCase_       ,							"do_normalize"				)				)
										self.assertTrue(hasattr(UpperCAmelCase_       ,							"do_resize"				)				)
										self.assertTrue(hasattr(UpperCAmelCase_       ,							"size"				)				)

							def 							_A	(		self			:int				)				->  List[str]:


										'''simple docstring'''




										snake_case_				:					List[Any]   =       self.image_processing_class.from_dict(self.image_processor_dict				)
										self.assertEqual(image_processor.size       ,							{"shortest_edge": 18, "longest_edge": 1_333}				)
										self.assertEqual(image_processor.do_pad       ,							UpperCAmelCase_				)

										snake_case_				:					Dict   =       self.image_processing_class.from_dict(
										    self.image_processor_dict       ,							size=42       ,							max_size=84       ,							pad_and_return_pixel_mask=UpperCAmelCase_				)
										self.assertEqual(image_processor.size       ,							{"shortest_edge": 42, "longest_edge": 84}				)
										self.assertEqual(image_processor.do_pad       ,							UpperCAmelCase_				)

							def 							_A	(		self			:int				)				->  int:


										'''simple docstring'''




										pass

							def 							_A	(		self			:List[Any]				)				->  Any:


										'''simple docstring'''




										snake_case_				:					Tuple   =       self.image_processing_class(**self.image_processor_dict				)
										# create random PIL images
										snake_case_				:					Any   =       prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=UpperCAmelCase_				)
										for image in image_inputs:
													self.assertIsInstance(UpperCAmelCase_       ,							Image.Image				)

										# Test not batched input
										snake_case_				:					List[Any]   =       image_processing(image_inputs[0]       ,							return_tensors="pt"				).pixel_values

										snake_case_,	snake_case_				:					List[Any]   =       self.image_processor_tester.get_expected_values(UpperCAmelCase_				)

										self.assertEqual(
										    encoded_images.shape       ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,							)

										# Test batched
										snake_case_,	snake_case_				:					Dict   =       self.image_processor_tester.get_expected_values(UpperCAmelCase_       ,							batched=UpperCAmelCase_				)

										snake_case_				:					Any   =       image_processing(UpperCAmelCase_       ,							return_tensors="pt"				).pixel_values
										self.assertEqual(
										    encoded_images.shape       ,							(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )       ,							)

							def 							_A	(		self			:Dict				)				->  int:


										'''simple docstring'''




										snake_case_				:					str   =       self.image_processing_class(**self.image_processor_dict				)
										# create random numpy tensors
										snake_case_				:					Dict   =       prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=UpperCAmelCase_       ,							numpify=UpperCAmelCase_				)
										for image in image_inputs:
													self.assertIsInstance(UpperCAmelCase_       ,							np.ndarray				)

										# Test not batched input
										snake_case_				:					str   =       image_processing(image_inputs[0]       ,							return_tensors="pt"				).pixel_values

										snake_case_,	snake_case_				:					Any   =       self.image_processor_tester.get_expected_values(UpperCAmelCase_				)

										self.assertEqual(
										    encoded_images.shape       ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,							)

										# Test batched
										snake_case_				:					Tuple   =       image_processing(UpperCAmelCase_       ,							return_tensors="pt"				).pixel_values

										snake_case_,	snake_case_				:					Any   =       self.image_processor_tester.get_expected_values(UpperCAmelCase_       ,							batched=UpperCAmelCase_				)

										self.assertEqual(
										    encoded_images.shape       ,							(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )       ,							)

							def 							_A	(		self			:List[str]				)				->  int:


										'''simple docstring'''




										snake_case_				:					Union[str, Any]   =       self.image_processing_class(**self.image_processor_dict				)
										# create random PyTorch tensors
										snake_case_				:					Optional[int]   =       prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=UpperCAmelCase_       ,							torchify=UpperCAmelCase_				)
										for image in image_inputs:
													self.assertIsInstance(UpperCAmelCase_       ,							torch.Tensor				)

										# Test not batched input
										snake_case_				:					int   =       image_processing(image_inputs[0]       ,							return_tensors="pt"				).pixel_values

										snake_case_,	snake_case_				:					List[Any]   =       self.image_processor_tester.get_expected_values(UpperCAmelCase_				)

										self.assertEqual(
										    encoded_images.shape       ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,							)

										# Test batched
										snake_case_				:					Tuple   =       image_processing(UpperCAmelCase_       ,							return_tensors="pt"				).pixel_values

										snake_case_,	snake_case_				:					int   =       self.image_processor_tester.get_expected_values(UpperCAmelCase_       ,							batched=UpperCAmelCase_				)

										self.assertEqual(
										    encoded_images.shape       ,							(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )       ,							)

							@slow
							def 							_A	(		self			:Optional[int]				)				->  Dict:


										'''simple docstring'''




										snake_case_				:					Dict   =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
										with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt"       ,							"r"				) as f:
													snake_case_				:					List[Any]   =       json.loads(f.read()				)

										snake_case_				:					Tuple   =       {"image_id": 39_769, "annotations": target}

										# encode them
										snake_case_				:					Any   =       ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50"				)
										snake_case_				:					Optional[Any]   =       image_processing(images=UpperCAmelCase_       ,							annotations=UpperCAmelCase_       ,							return_tensors="pt"				)

										# verify pixel values
										snake_case_				:					List[Any]   =       torch.Size([1, 3, 800, 1_066]				)
										self.assertEqual(encoding["pixel_values"].shape       ,							UpperCAmelCase_				)

										snake_case_				:					Tuple   =       torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]				)
										self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]       ,							UpperCAmelCase_       ,							atol=1E-4				)				)

										# verify area
										snake_case_				:					Tuple   =       torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["area"]       ,							UpperCAmelCase_				)				)
										# verify boxes
										snake_case_				:					int   =       torch.Size([6, 4]				)
										self.assertEqual(encoding["labels"][0]["boxes"].shape       ,							UpperCAmelCase_				)
										snake_case_				:					Any   =       torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]       ,							UpperCAmelCase_       ,							atol=1E-3				)				)
										# verify image_id
										snake_case_				:					Union[str, Any]   =       torch.tensor([39_769]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]       ,							UpperCAmelCase_				)				)
										# verify is_crowd
										snake_case_				:					Dict   =       torch.tensor([0, 0, 0, 0, 0, 0]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]       ,							UpperCAmelCase_				)				)
										# verify class_labels
										snake_case_				:					Any   =       torch.tensor([75, 75, 63, 65, 17, 17]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]       ,							UpperCAmelCase_				)				)
										# verify orig_size
										snake_case_				:					int   =       torch.tensor([480, 640]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]       ,							UpperCAmelCase_				)				)
										# verify size
										snake_case_				:					str   =       torch.tensor([800, 1_066]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["size"]       ,							UpperCAmelCase_				)				)






							@slow
							def 							_A	(		self			:List[Any]				)				->  List[str]:


										'''simple docstring'''




										snake_case_				:					Any   =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
										with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"       ,							"r"				) as f:
													snake_case_				:					Optional[int]   =       json.loads(f.read()				)

										snake_case_				:					Optional[Any]   =       {"file_name": "000000039769.png", "image_id": 39_769, "segments_info": target}

										snake_case_				:					List[str]   =       pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic"				)

										# encode them
										snake_case_				:					Union[str, Any]   =       ConditionalDetrImageProcessor(format="coco_panoptic"				)
										snake_case_				:					Tuple   =       image_processing(images=UpperCAmelCase_       ,							annotations=UpperCAmelCase_       ,							masks_path=UpperCAmelCase_       ,							return_tensors="pt"				)

										# verify pixel values
										snake_case_				:					Dict   =       torch.Size([1, 3, 800, 1_066]				)
										self.assertEqual(encoding["pixel_values"].shape       ,							UpperCAmelCase_				)

										snake_case_				:					List[str]   =       torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]				)
										self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]       ,							UpperCAmelCase_       ,							atol=1E-4				)				)

										# verify area
										snake_case_				:					Dict   =       torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["area"]       ,							UpperCAmelCase_				)				)
										# verify boxes
										snake_case_				:					Optional[int]   =       torch.Size([6, 4]				)
										self.assertEqual(encoding["labels"][0]["boxes"].shape       ,							UpperCAmelCase_				)
										snake_case_				:					Union[str, Any]   =       torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]       ,							UpperCAmelCase_       ,							atol=1E-3				)				)
										# verify image_id
										snake_case_				:					Dict   =       torch.tensor([39_769]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]       ,							UpperCAmelCase_				)				)
										# verify is_crowd
										snake_case_				:					Any   =       torch.tensor([0, 0, 0, 0, 0, 0]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]       ,							UpperCAmelCase_				)				)
										# verify class_labels
										snake_case_				:					Union[str, Any]   =       torch.tensor([17, 17, 63, 75, 75, 93]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]       ,							UpperCAmelCase_				)				)
										# verify masks
										snake_case_				:					Any   =       822_873
										self.assertEqual(encoding["labels"][0]["masks"].sum().item()       ,							UpperCAmelCase_				)
										# verify orig_size
										snake_case_				:					Optional[Any]   =       torch.tensor([480, 640]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]       ,							UpperCAmelCase_				)				)
										# verify size
										snake_case_				:					Optional[int]   =       torch.tensor([800, 1_066]				)
										self.assertTrue(torch.allclose(encoding["labels"][0]["size"]       ,							UpperCAmelCase_				)				)












'''simple docstring'''




from scipy.stats import spearmanr

import datasets


__lowerCamelCase   :					str   							=					'''
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
'''

__lowerCamelCase   :					int   							=					'''
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {\'spearmanr\': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results[\'spearmanr\'])
        -0.7
        >>> print(round(results[\'spearmanr_pvalue\'], 2))
        0.19
'''

__lowerCamelCase   :					List[str]   							=					R'''\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
'''







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,					_KWARGS_DESCRIPTION							)
class    A_	(datasets.Metric							):
							"""simple docstring"""




							def 							_A	(		self			:str				)				->  Union[str, Any]:


										'''simple docstring'''




										return datasets.MetricInfo(
										    description=_DESCRIPTION       ,							citation=_CITATION       ,							inputs_description=_KWARGS_DESCRIPTION       ,							features=datasets.Features(
										        {
										            "predictions": datasets.Value("float"				),
										            "references": datasets.Value("float"				),
										        }				)       ,							reference_urls=["https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"]       ,							)






							def 							_A	(		self			:Optional[int]       ,							lowerCAmelCase__			:Optional[Any]       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:Optional[Any]=False				)				->  List[Any]:


										'''simple docstring'''




										snake_case_				:					Optional[Any]   =       spearmanr(lowerCAmelCase__       ,							lowerCAmelCase__				)
										if return_pvalue:
													return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
										else:
													return {"spearmanr": results[0]}




