





import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
      from PIL import Image

      from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
      import torch

if is_tf_available():
      import tensorflow as tf

@require_vision
@require_torchvision
class    _UpperCAmelCase							(		unittest.TestCase     ):
      def 		_lowerCamelCase      (		self       ):
         A_     :				List[Any]			      =	tempfile.mkdtemp()
         A_     :				List[str]			      =	SamImageProcessor()
         A_     :				Tuple			      =	SamProcessor(a__       )
         processor.save_pretrained(self.tmpdirname       )
      def 		_lowerCamelCase      (		self      ,       **a__       ):
         return AutoProcessor.from_pretrained(self.tmpdirname      ,       **a__       ).image_processor
      def 		_lowerCamelCase      (		self       ):
         shutil.rmtree(self.tmpdirname       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				Tuple			      =	[np.random.randint(255      ,       size=(3, 30, 400)      ,       dtype=np.uinta       )]

         A_     :				Any			      =	[Image.fromarray(np.moveaxis(a__      ,       0      ,       -1       )       ) for x in image_inputs]

         return image_inputs
      def 		_lowerCamelCase      (		self       ):
         A_     :				Dict			      =	SamProcessor(image_processor=self.get_image_processor()       )
         processor.save_pretrained(self.tmpdirname       )

         A_     :				Dict			      =	self.get_image_processor(do_normalize=a__      ,       padding_value=1.0       )

         A_     :				Tuple			      =	SamProcessor.from_pretrained(self.tmpdirname      ,       do_normalize=a__      ,       padding_value=1.0       )

         self.assertEqual(processor.image_processor.to_json_string()      ,       image_processor_add_kwargs.to_json_string()       )
         self.assertIsInstance(processor.image_processor      ,       a__       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				str			      =	self.get_image_processor()

         A_     :				str			      =	SamProcessor(image_processor=a__       )

         A_     :				Union[str, Any]			      =	self.prepare_image_inputs()

         A_     :				List[str]			      =	image_processor(a__      ,       return_tensors="""np"""       )
         A_     :				Any			      =	processor(images=a__      ,       return_tensors="""np"""       )

         input_feat_extract.pop("""original_sizes"""       )  # pop original_sizes as it is popped in the processor
         input_feat_extract.pop("""reshaped_input_sizes"""       )  # pop original_sizes as it is popped in the processor

         for key in input_feat_extract.keys():
            self.assertAlmostEqual(input_feat_extract[key].sum()      ,       input_processor[key].sum()      ,       delta=1E-2       )






      @require_torch
      def 		_lowerCamelCase      (		self       ):
         A_     :				Union[str, Any]			      =	self.get_image_processor()

         A_     :				Optional[int]			      =	SamProcessor(image_processor=a__       )
         A_     :				int			      =	[torch.ones((1, 3, 5, 5)       )]

         A_     :				Optional[int]			      =	[[1764, 2646]]

         A_     :				Tuple			      =	[[683, 1024]]
         A_     :				List[Any]			      =	processor.post_process_masks(a__      ,       a__      ,       a__       )
         self.assertEqual(masks[0].shape      ,       (1, 3, 1764, 2646)       )

         A_     :				List[str]			      =	processor.post_process_masks(
             a__      ,       torch.tensor(a__       )      ,       torch.tensor(a__       )       )
         self.assertEqual(masks[0].shape      ,       (1, 3, 1764, 2646)       )

         # should also work with np
         A_     :				str			      =	[np.ones((1, 3, 5, 5)       )]
         A_     :				Optional[Any]			      =	processor.post_process_masks(a__      ,       np.array(a__       )      ,       np.array(a__       )       )

         self.assertEqual(masks[0].shape      ,       (1, 3, 1764, 2646)       )

         A_     :				Tuple			      =	[[1, 0], [0, 1]]
         with self.assertRaises(a__       ):
            A_     :				str			      =	processor.post_process_masks(a__      ,       np.array(a__       )      ,       np.array(a__       )       )






@require_vision
@require_tf
class    _UpperCAmelCase							(		unittest.TestCase     ):
      def 		_lowerCamelCase      (		self       ):
         A_     :				Optional[int]			      =	tempfile.mkdtemp()
         A_     :				List[Any]			      =	SamImageProcessor()
         A_     :				Optional[int]			      =	SamProcessor(a__       )
         processor.save_pretrained(self.tmpdirname       )
      def 		_lowerCamelCase      (		self      ,       **a__       ):
         return AutoProcessor.from_pretrained(self.tmpdirname      ,       **a__       ).image_processor
      def 		_lowerCamelCase      (		self       ):
         shutil.rmtree(self.tmpdirname       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				int			      =	[np.random.randint(255      ,       size=(3, 30, 400)      ,       dtype=np.uinta       )]

         A_     :				Tuple			      =	[Image.fromarray(np.moveaxis(a__      ,       0      ,       -1       )       ) for x in image_inputs]

         return image_inputs
      def 		_lowerCamelCase      (		self       ):
         A_     :				int			      =	SamProcessor(image_processor=self.get_image_processor()       )
         processor.save_pretrained(self.tmpdirname       )

         A_     :				Optional[Any]			      =	self.get_image_processor(do_normalize=a__      ,       padding_value=1.0       )

         A_     :				str			      =	SamProcessor.from_pretrained(self.tmpdirname      ,       do_normalize=a__      ,       padding_value=1.0       )

         self.assertEqual(processor.image_processor.to_json_string()      ,       image_processor_add_kwargs.to_json_string()       )
         self.assertIsInstance(processor.image_processor      ,       a__       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				Dict			      =	self.get_image_processor()

         A_     :				Union[str, Any]			      =	SamProcessor(image_processor=a__       )

         A_     :				Optional[int]			      =	self.prepare_image_inputs()

         A_     :				Union[str, Any]			      =	image_processor(a__      ,       return_tensors="""np"""       )
         A_     :				Tuple			      =	processor(images=a__      ,       return_tensors="""np"""       )

         input_feat_extract.pop("""original_sizes"""       )  # pop original_sizes as it is popped in the processor
         input_feat_extract.pop("""reshaped_input_sizes"""       )  # pop reshaped_input_sizes as it is popped in the processor

         for key in input_feat_extract.keys():
            self.assertAlmostEqual(input_feat_extract[key].sum()      ,       input_processor[key].sum()      ,       delta=1E-2       )






      @require_tf
      def 		_lowerCamelCase      (		self       ):
         A_     :				Union[str, Any]			      =	self.get_image_processor()

         A_     :				Any			      =	SamProcessor(image_processor=a__       )
         A_     :				Optional[Any]			      =	[tf.ones((1, 3, 5, 5)       )]

         A_     :				Union[str, Any]			      =	[[1764, 2646]]

         A_     :				Any			      =	[[683, 1024]]
         A_     :				List[str]			      =	processor.post_process_masks(a__      ,       a__      ,       a__      ,       return_tensors="""tf"""       )
         self.assertEqual(masks[0].shape      ,       (1, 3, 1764, 2646)       )

         A_     :				int			      =	processor.post_process_masks(
             a__      ,       tf.convert_to_tensor(a__       )      ,       tf.convert_to_tensor(a__       )      ,       return_tensors="""tf"""      ,       )
         self.assertEqual(masks[0].shape      ,       (1, 3, 1764, 2646)       )

         # should also work with np
         A_     :				Dict			      =	[np.ones((1, 3, 5, 5)       )]
         A_     :				Union[str, Any]			      =	processor.post_process_masks(
             a__      ,       np.array(a__       )      ,       np.array(a__       )      ,       return_tensors="""tf"""       )

         self.assertEqual(masks[0].shape      ,       (1, 3, 1764, 2646)       )

         A_     :				str			      =	[[1, 0], [0, 1]]
         with self.assertRaises(tf.errors.InvalidArgumentError       ):
            A_     :				Tuple			      =	processor.post_process_masks(
                a__      ,       np.array(a__       )      ,       np.array(a__       )      ,       return_tensors="""tf"""       )






@require_vision
@require_torchvision
class    _UpperCAmelCase							(		unittest.TestCase     ):
      def 		_lowerCamelCase      (		self       ):
         A_     :				Optional[Any]			      =	tempfile.mkdtemp()
         A_     :				List[Any]			      =	SamImageProcessor()
         A_     :				str			      =	SamProcessor(a__       )
         processor.save_pretrained(self.tmpdirname       )
      def 		_lowerCamelCase      (		self      ,       **a__       ):
         return AutoProcessor.from_pretrained(self.tmpdirname      ,       **a__       ).image_processor
      def 		_lowerCamelCase      (		self       ):
         shutil.rmtree(self.tmpdirname       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				List[str]			      =	[np.random.randint(255      ,       size=(3, 30, 400)      ,       dtype=np.uinta       )]

         A_     :				Tuple			      =	[Image.fromarray(np.moveaxis(a__      ,       0      ,       -1       )       ) for x in image_inputs]

         return image_inputs
      @is_pt_tf_cross_test
      def 		_lowerCamelCase      (		self       ):
         A_     :				Dict			      =	self.get_image_processor()

         A_     :				Union[str, Any]			      =	SamProcessor(image_processor=a__       )
         A_     :				Union[str, Any]			      =	np.random.randint(0      ,       2      ,       size=(1, 3, 5, 5)       ).astype(np.floataa       )
         A_     :				Tuple			      =	[tf.convert_to_tensor(a__       )]
         A_     :				Union[str, Any]			      =	[torch.tensor(a__       )]

         A_     :				str			      =	[[1764, 2646]]

         A_     :				List[str]			      =	[[683, 1024]]
         A_     :				List[str]			      =	processor.post_process_masks(
             a__      ,       a__      ,       a__      ,       return_tensors="""tf"""       )
         A_     :				List[str]			      =	processor.post_process_masks(
             a__      ,       a__      ,       a__      ,       return_tensors="""pt"""       )

         self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()       )       )






      @is_pt_tf_cross_test
      def 		_lowerCamelCase      (		self       ):
         A_     :				Tuple			      =	self.get_image_processor()

         A_     :				Any			      =	SamProcessor(image_processor=a__       )

         A_     :				str			      =	self.prepare_image_inputs()

         A_     :				List[str]			      =	image_processor(a__      ,       return_tensors="""pt"""       )["""pixel_values"""].numpy()
         A_     :				Dict			      =	processor(images=a__      ,       return_tensors="""pt"""       )["""pixel_values"""].numpy()

         A_     :				Optional[Any]			      =	image_processor(a__      ,       return_tensors="""tf"""       )["""pixel_values"""].numpy()
         A_     :				Optional[Any]			      =	processor(images=a__      ,       return_tensors="""tf"""       )["""pixel_values"""].numpy()

         self.assertTrue(np.allclose(a__      ,       a__       )       )
         self.assertTrue(np.allclose(a__      ,       a__       )       )
         self.assertTrue(np.allclose(a__      ,       a__       )       )













import datasets

from .evaluate import evaluate


_lowerCAmelCase 				=     """\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
"""

_lowerCAmelCase 				=     """
This metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.
"""

_lowerCAmelCase 				=     """
Computes SQuAD scores (F1 and EM).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair as given in the references (see below)
        - 'prediction_text': the text of the answer
    references: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair (see above),
        - 'answers': a Dict in the SQuAD dataset format
            {
                'text': list of possible texts for the answer, as a list of strings
                'answer_start': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    'exact_match': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
Examples:

    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]
    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]
    >>> squad_metric = datasets.load_metric(\"squad\")
    >>> results = squad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 100.0, 'f1': 100.0}
"""

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,       _KWARGS_DESCRIPTION     )
class    _UpperCAmelCase							(		datasets.Metric     ):
      def 		_lowerCamelCase      (		self       ):
         return datasets.MetricInfo(
             description=_DESCRIPTION      ,       citation=_CITATION      ,       inputs_description=_KWARGS_DESCRIPTION      ,       features=datasets.Features(
                 {
                     """predictions""": {"""id""": datasets.Value("""string"""       ), """prediction_text""": datasets.Value("""string"""       )},
                     """references""": {
                         """id""": datasets.Value("""string"""       ),
                         """answers""": datasets.features.Sequence(
                             {
                                 """text""": datasets.Value("""string"""       ),
                                 """answer_start""": datasets.Value("""int32"""       ),
                             }       ),
                     },
                 }       )      ,       codebase_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""]      ,       reference_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""]      ,       )






      def 		_lowerCamelCase      (		self      ,       a__      ,       a__       ):
         A_     :				Union[str, Any]			      =	{prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions}
         A_     :				Optional[Any]			      =	[
             {
                 """paragraphs""": [
                     {
                         """qas""": [
                             {
                                 """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]],
                                 """id""": ref["""id"""],
                             }
                             for ref in references
                         ]
                     }
                 ]
             }
         ]
         A_     :				Union[str, Any]			      =	evaluate(dataset=a__      ,       predictions=a__       )
         return score






