





'''simple docstring'''






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


__UpperCamelCase					    =	logging.get_logger(__name__)


if is_vision_available():
	import PIL




class  _A (					__lowercase		):
		lowercase__:   str				     =   ['''pixel_values''']

		def __init__(   self					:   Union[str, Any]  ,      __magic_name__					:   bool = True  ,      __magic_name__					:   Dict[str, int] = None  ,      __magic_name__					:   PILImageResampling = PILImageResampling.BICUBIC  ,      __magic_name__					:   bool = True  ,      __magic_name__					:   Dict[str, int] = None  ,      __magic_name__					:   bool = True  ,      __magic_name__					:   Union[int, float] = 1 / 2_55  ,      __magic_name__					:   bool = True  ,      __magic_name__					:   Optional[Union[float, List[float]]] = None  ,      __magic_name__					:   Optional[Union[float, List[float]]] = None  ,      __magic_name__					:   bool = True  ,      **__magic_name__					:   Optional[Any]  ,      )					->    None:


					"""simple docstring"""

					super().__init__(**__magic_name__			)
					__snake_case					:      Optional[Any]							      =     size if size is not None else {"""shortest_edge""": 2_24}
					__snake_case					:      Union[str, Any]							      =     get_size_dict(__magic_name__  ,      default_to_square=__magic_name__			)
					__snake_case					:      Any							      =     crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24}
					__snake_case					:      str							      =     get_size_dict(__magic_name__  ,      default_to_square=__magic_name__  ,      param_name="""crop_size"""			)

					__snake_case					:      Any							      =     do_resize
					__snake_case					:      Optional[Any]							      =     size
					__snake_case					:      List[str]							      =     resample
					__snake_case					:      Optional[int]							      =     do_center_crop
					__snake_case					:      List[str]							      =     crop_size
					__snake_case					:      Dict							      =     do_rescale
					__snake_case					:      List[Any]							      =     rescale_factor
					__snake_case					:      Tuple							      =     do_normalize
					__snake_case					:      Tuple							      =     image_mean if image_mean is not None else OPENAI_CLIP_MEAN
					__snake_case					:      Dict							      =     image_std if image_std is not None else OPENAI_CLIP_STD
					__snake_case					:      Tuple							      =     do_convert_rgb

		def 	lowercase__     (   self					:   int  ,      __magic_name__					:   np.ndarray  ,      __magic_name__					:   Dict[str, int]  ,      __magic_name__					:   PILImageResampling = PILImageResampling.BICUBIC  ,      __magic_name__					:   Optional[Union[str, ChannelDimension]] = None  ,      **__magic_name__					:   Tuple  ,      )					->    np.ndarray:


					"""simple docstring"""

					__snake_case					:      Optional[int]							      =     get_size_dict(__magic_name__  ,      default_to_square=__magic_name__			)
					if "shortest_edge" not in size:
								raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''			)
					__snake_case					:      Tuple							      =     get_resize_output_image_size(__magic_name__  ,      size=size["""shortest_edge"""]  ,      default_to_square=__magic_name__			)
					return resize(__magic_name__  ,      size=__magic_name__  ,      resample=__magic_name__  ,      data_format=__magic_name__  ,      **__magic_name__			)

		def 	lowercase__     (   self					:   str  ,      __magic_name__					:   np.ndarray  ,      __magic_name__					:   Dict[str, int]  ,      __magic_name__					:   Optional[Union[str, ChannelDimension]] = None  ,      **__magic_name__					:   Dict  ,      )					->    np.ndarray:


					"""simple docstring"""

					__snake_case					:      str							      =     get_size_dict(__magic_name__			)
					if "height" not in size or "width" not in size:
								raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''			)
					return center_crop(__magic_name__  ,      size=(size["""height"""], size["""width"""])  ,      data_format=__magic_name__  ,      **__magic_name__			)

		def 	lowercase__     (   self					:   List[Any]  ,      __magic_name__					:   np.ndarray  ,      __magic_name__					:   Union[int, float]  ,      __magic_name__					:   Optional[Union[str, ChannelDimension]] = None  ,      **__magic_name__					:   Optional[int]  ,      )					->    Tuple:


					"""simple docstring"""

					return rescale(__magic_name__  ,      scale=__magic_name__  ,      data_format=__magic_name__  ,      **__magic_name__			)

		def 	lowercase__     (   self					:   List[str]  ,      __magic_name__					:   np.ndarray  ,      __magic_name__					:   Union[float, List[float]]  ,      __magic_name__					:   Union[float, List[float]]  ,      __magic_name__					:   Optional[Union[str, ChannelDimension]] = None  ,      **__magic_name__					:   str  ,      )					->    np.ndarray:


					"""simple docstring"""

					return normalize(__magic_name__  ,      mean=__magic_name__  ,      std=__magic_name__  ,      data_format=__magic_name__  ,      **__magic_name__			)

		def 	lowercase__     (   self					:   Dict  ,      __magic_name__					:   ImageInput  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   Dict[str, int] = None  ,      __magic_name__					:   PILImageResampling = None  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   int = None  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   float = None  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   Optional[Union[float, List[float]]] = None  ,      __magic_name__					:   Optional[Union[float, List[float]]] = None  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   Optional[Union[str, TensorType]] = None  ,      __magic_name__					:   Optional[ChannelDimension] = ChannelDimension.FIRST  ,      **__magic_name__					:   Tuple  ,      )					->    PIL.Image.Image:


					"""simple docstring"""

					__snake_case					:      List[str]							      =     do_resize if do_resize is not None else self.do_resize
					__snake_case					:      Any							      =     size if size is not None else self.size
					__snake_case					:      List[str]							      =     get_size_dict(__magic_name__  ,      param_name="""size"""  ,      default_to_square=__magic_name__			)
					__snake_case					:      Dict							      =     resample if resample is not None else self.resample
					__snake_case					:      Union[str, Any]							      =     do_center_crop if do_center_crop is not None else self.do_center_crop
					__snake_case					:      Union[str, Any]							      =     crop_size if crop_size is not None else self.crop_size
					__snake_case					:      str							      =     get_size_dict(__magic_name__  ,      param_name="""crop_size"""  ,      default_to_square=__magic_name__			)
					__snake_case					:      str							      =     do_rescale if do_rescale is not None else self.do_rescale
					__snake_case					:      Dict							      =     rescale_factor if rescale_factor is not None else self.rescale_factor
					__snake_case					:      int							      =     do_normalize if do_normalize is not None else self.do_normalize
					__snake_case					:      Tuple							      =     image_mean if image_mean is not None else self.image_mean
					__snake_case					:      List[Any]							      =     image_std if image_std is not None else self.image_std
					__snake_case					:      Union[str, Any]							      =     do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

					__snake_case					:      Optional[int]							      =     make_list_of_images(__magic_name__			)

					if not valid_images(__magic_name__			):
								raise ValueError(
								    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
								    """torch.Tensor, tf.Tensor or jax.ndarray."""			)

					if do_resize and size is None:
								raise ValueError("""Size must be specified if do_resize is True."""			)

					if do_center_crop and crop_size is None:
								raise ValueError("""Crop size must be specified if do_center_crop is True."""			)

					if do_rescale and rescale_factor is None:
								raise ValueError("""Rescale factor must be specified if do_rescale is True."""			)

					if do_normalize and (image_mean is None or image_std is None):
								raise ValueError("""Image mean and std must be specified if do_normalize is True."""			)

					# PIL RGBA images are converted to RGB
					if do_convert_rgb:
								__snake_case					:      List[str]							      =     [convert_to_rgb(__magic_name__			) for image in images]

					# All transformations expect numpy arrays.
					__snake_case					:      str							      =     [to_numpy_array(__magic_name__			) for image in images]

					if do_resize:
								__snake_case					:      List[str]							      =     [self.resize(image=__magic_name__  ,      size=__magic_name__  ,      resample=__magic_name__			) for image in images]

					if do_center_crop:
								__snake_case					:      Any							      =     [self.center_crop(image=__magic_name__  ,      size=__magic_name__			) for image in images]

					if do_rescale:
								__snake_case					:      Optional[Any]							      =     [self.rescale(image=__magic_name__  ,      scale=__magic_name__			) for image in images]

					if do_normalize:
								__snake_case					:      int							      =     [self.normalize(image=__magic_name__  ,      mean=__magic_name__  ,      std=__magic_name__			) for image in images]

					__snake_case					:      Union[str, Any]							      =     [to_channel_dimension_format(__magic_name__  ,      __magic_name__			) for image in images]

					__snake_case					:      List[Any]							      =     {"""pixel_values""": images}
					return BatchFeature(data=__magic_name__  ,      tensor_type=__magic_name__			)




'''simple docstring'''
import datasets

from .evaluate import evaluate


lowercase__						       =      "\\n@article{hendrycks2021cuad,\n      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n      journal={arXiv preprint arXiv:2103.06268},\n      year={2021}\n}\n"

lowercase__						       =      "\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n"

lowercase__						       =      "\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - 'id': id of the question-answer pair as given in the references (see below)\n        - 'prediction_text': list of possible texts for the answer, as a list of strings\n        depending on a threshold on the confidence probability of each prediction.\n    references: List of question-answers dictionaries with the following key-values:\n        - 'id': id of the question-answer pair (see above),\n        - 'answers': a Dict in the CUAD dataset format\n            {\n                'text': list of possible texts for the answer, as a list of strings\n                'answer_start': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    'exact_match': Exact match (the normalized answer exactly match the gold answer)\n    'f1': The F-score of predicted tokens versus the gold answer\n    'aupr': Area Under the Precision-Recall curve\n    'prec_at_80_recall': Precision at 80% recall\n    'prec_at_90_recall': Precision at 90% recall\nExamples:\n    >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]\n    >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]\n    >>> cuad_metric = datasets.load_metric(\"cuad\")\n    >>> results = cuad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0}\n"






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







		"""simple docstring"""

		def       lowerCAmelCase				(      self				:			Optional[int]      )						->			Tuple:






				"""simple docstring"""







				return datasets.MetricInfo(
				    description=_DESCRIPTION  ,	citation=_CITATION  ,	inputs_description=_KWARGS_DESCRIPTION  ,	features=datasets.Features(
				        {
				            '''predictions''': {
				                '''id''': datasets.Value('''string'''      ),
				                '''prediction_text''': datasets.features.Sequence(datasets.Value('''string'''      )      ),
				            },
				            '''references''': {
				                '''id''': datasets.Value('''string'''      ),
				                '''answers''': datasets.features.Sequence(
				                    {
				                        '''text''': datasets.Value('''string'''      ),
				                        '''answer_start''': datasets.Value('''int32'''      ),
				                    }      ),
				            },
				        }      )  ,	codebase_urls=['''https://www.atticusprojectai.org/cuad''']  ,	reference_urls=['''https://www.atticusprojectai.org/cuad''']  ,	)



		def       lowerCAmelCase				(      self				:			str  ,	UpperCamelCase__				:			int  ,	UpperCamelCase__				:			str      )						->			Optional[Any]:






				"""simple docstring"""







				snake_case  :       Tuple     			=						{prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions}
				snake_case  :       Dict     			=						[
				    {
				        '''paragraphs''': [
				            {
				                '''qas''': [
				                    {
				                        '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']],
				                        '''id''': ref['''id'''],
				                    }
				                    for ref in references
				                ]
				            }
				        ]
				    }
				]
				snake_case  :       int     			=						evaluate(dataset=UpperCamelCase__  ,	predictions=UpperCamelCase__      )
				return score


