






import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


A_			:Any	    =		'''\
@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}
}
'''

A_			:Union[str, Any]	    =		'''
This metric wrap the official scoring script for version 2 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.

SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions
written adversarially by crowdworkers to look similar to answerable ones.
To do well on SQuAD2.0, systems must not only answer questions when possible, but also
determine when no answer is supported by the paragraph and abstain from answering.
'''

A_			:int	    =		'''
Computes SQuAD v2 scores (F1 and EM).
Args:
    predictions: List of triple for question-answers to score with the following elements:
        - the question-answer \'id\' field as given in the references (see below)
        - the text of the answer
        - the probability that the question has no answer
    references: List of question-answers dictionaries with the following key-values:
            - \'id\': id of the question-answer pair (see above),
            - \'answers\': a list of Dict {\'text\': text of the answer as a string}
    no_answer_threshold: float
        Probability threshold to decide that a question has no answer.
Returns:
    \'exact\': Exact match (the normalized answer exactly match the gold answer)
    \'f1\': The F-score of predicted tokens versus the gold answer
    \'total\': Number of score considered
    \'HasAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'HasAns_f1\': The F-score of predicted tokens versus the gold answer
    \'HasAns_total\': Number of score considered
    \'NoAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'NoAns_f1\': The F-score of predicted tokens versus the gold answer
    \'NoAns_total\': Number of score considered
    \'best_exact\': Best exact match (with varying threshold)
    \'best_exact_thresh\': No-answer probability threshold associated to the best exact match
    \'best_f1\': Best F1 (with varying threshold)
    \'best_f1_thresh\': No-answer probability threshold associated to the best F1
Examples:

    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\', \'no_answer_probability\': 0.}]
    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]
    >>> squad_v2_metric = datasets.load_metric("squad_v2")
    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact\': 100.0, \'f1\': 100.0, \'total\': 1, \'HasAns_exact\': 100.0, \'HasAns_f1\': 100.0, \'HasAns_total\': 1, \'best_exact\': 100.0, \'best_exact_thresh\': 0.0, \'best_f1\': 100.0, \'best_f1_thresh\': 0.0}
'''




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





				"""simple docstring"""







				def  __lowercase				(					self       ):




									"""simple docstring"""

									return datasets.MetricInfo(
									    description=_DESCRIPTION				,    citation=_CITATION				,    inputs_description=_KWARGS_DESCRIPTION				,    features=datasets.Features(
									        {
									            'predictions': {
									                'id': datasets.Value('string'       ),
									                'prediction_text': datasets.Value('string'       ),
									                'no_answer_probability': datasets.Value('float32'       ),
									            },
									            '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  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__=1.0       ):




									"""simple docstring"""

									__UpperCamelCase :   List[Any]									={p['id']: p['no_answer_probability'] for p in predictions}
									__UpperCamelCase :   Optional[int]									=[{'paragraphs': [{'qas': references}]}]
									__UpperCamelCase :   str									={p['id']: p['prediction_text'] for p in predictions}

									__UpperCamelCase :   Union[str, Any]									=make_qid_to_has_ans(lowerCamelCase__       )  # maps qid to True/False
									__UpperCamelCase :   Union[str, Any]									=[k for k, v in qid_to_has_ans.items() if v]
									__UpperCamelCase :   Optional[int]									=[k for k, v in qid_to_has_ans.items() if not v]

									__UpperCamelCase						,							__UpperCamelCase :   Tuple									=get_raw_scores(lowerCamelCase__				,    lowerCamelCase__       )
									__UpperCamelCase :   Dict									=apply_no_ans_threshold(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )
									__UpperCamelCase :   str									=apply_no_ans_threshold(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )
									__UpperCamelCase :   str									=make_eval_dict(lowerCamelCase__				,    lowerCamelCase__       )

									if has_ans_qids:
														__UpperCamelCase :   int									=make_eval_dict(lowerCamelCase__				,    lowerCamelCase__				,    qid_list=lowerCamelCase__       )
														merge_eval(lowerCamelCase__				,    lowerCamelCase__				,    'HasAns'       )
									if no_ans_qids:
														__UpperCamelCase :   Any									=make_eval_dict(lowerCamelCase__				,    lowerCamelCase__				,    qid_list=lowerCamelCase__       )
														merge_eval(lowerCamelCase__				,    lowerCamelCase__				,    'NoAns'       )
									find_all_best_thresh(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )
									return dict(lowerCamelCase__       )









import colorsys
import io

import cva
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import numpy as np
import torch
from matplotlib.backends.backend_agg import FigureCanvasAgg

from utils import img_tensorize


A_			:Tuple	    =		1000




class 							__A	:





				"""simple docstring"""







				def __init__(					self				,    lowerCamelCase__				,    lowerCamelCase__=1.2				,    lowerCamelCase__="g"				,    lowerCamelCase__=0.5				,    lowerCamelCase__="-"				,    lowerCamelCase__="test_out.jpg"				,    lowerCamelCase__=True				,    lowerCamelCase__=False				,    lowerCamelCase__=None				,    lowerCamelCase__=None				,    lowerCamelCase__=0.7				,    ):




									"""simple docstring"""

									if isinstance(lowerCamelCase__				,    torch.Tensor       ):
														__UpperCamelCase :   Union[str, Any]									=img.numpy().astype('np.uint8'       )
									if isinstance(lowerCamelCase__				,    lowerCamelCase__       ):
														__UpperCamelCase :   List[str]									=img_tensorize(lowerCamelCase__       )
									assert isinstance(lowerCamelCase__				,    np.ndarray       )

									__UpperCamelCase						,							__UpperCamelCase :   Any									=img.shape[1], img.shape[0]
									__UpperCamelCase :   Any									=mplfigure.Figure(frameon=lowerCamelCase__       )
									__UpperCamelCase :   Any									=fig.get_dpi()
									__UpperCamelCase :   Optional[Any]									=(width * scale + 1E-2) / dpi
									__UpperCamelCase :   Optional[Any]									=(height * scale + 1E-2) / dpi
									fig.set_size_inches(lowerCamelCase__				,    lowerCamelCase__       )
									__UpperCamelCase :   Dict									=fig.add_axes([0.0, 0.0, 1.0, 1.0]       )
									ax.axis('off'       )
									ax.set_xlim(0.0				,    lowerCamelCase__       )
									ax.set_ylim(lowerCamelCase__       )

									__UpperCamelCase :   List[Any]									=saveas
									__UpperCamelCase :   Any									=rgb
									__UpperCamelCase :   int									=pynb
									__UpperCamelCase :   Optional[int]									=img
									__UpperCamelCase :   List[Any]									=edgecolor
									__UpperCamelCase :   List[str]									=0.5
									__UpperCamelCase :   Optional[Any]									=linestyle
									__UpperCamelCase :   Dict									=int(np.sqrt(min(lowerCamelCase__				,    lowerCamelCase__       )       ) * scale // 3       )
									__UpperCamelCase :   List[Any]									=width
									__UpperCamelCase :   List[Any]									=height
									__UpperCamelCase :   int									=scale
									__UpperCamelCase :   List[str]									=fig
									__UpperCamelCase :   Union[str, Any]									=ax
									__UpperCamelCase :   Dict									=pad
									__UpperCamelCase :   List[Any]									=idaobj
									__UpperCamelCase :   List[Any]									=idaattr
									__UpperCamelCase :   List[str]									=FigureCanvasAgg(lowerCamelCase__       )


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__=None       ):




									"""simple docstring"""

									if color is None:
														__UpperCamelCase :   Optional[Any]									=self.edgecolor
									((__UpperCamelCase)						,							(__UpperCamelCase)						,							(__UpperCamelCase)						,							(__UpperCamelCase)) :   str									=box
									__UpperCamelCase :   List[Any]									=xa - xa
									__UpperCamelCase :   List[Any]									=ya - ya
									self.ax.add_patch(
									    mpl.patches.Rectangle(
									        (xa, ya)				,    lowerCamelCase__				,    lowerCamelCase__				,    fill=lowerCamelCase__				,    edgecolor=lowerCamelCase__				,    linewidth=self.font_size // 3				,    alpha=self.alpha				,    linestyle=self.linestyle				,    )       )


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__=None				,    lowerCamelCase__=None				,    lowerCamelCase__=None				,    lowerCamelCase__=None       ):




									"""simple docstring"""

									if len(boxes.shape       ) > 2:
														__UpperCamelCase :   List[str]									=boxes[0]
									if len(obj_ids.shape       ) > 1:
														__UpperCamelCase :   Tuple									=obj_ids[0]
									if len(obj_scores.shape       ) > 1:
														__UpperCamelCase :   int									=obj_scores[0]
									if len(attr_ids.shape       ) > 1:
														__UpperCamelCase :   str									=attr_ids[0]
									if len(attr_scores.shape       ) > 1:
														__UpperCamelCase :   Optional[int]									=attr_scores[0]
									if isinstance(lowerCamelCase__				,    torch.Tensor       ):
														__UpperCamelCase :   Dict									=boxes.numpy()
									if isinstance(lowerCamelCase__				,    lowerCamelCase__       ):
														__UpperCamelCase :   Tuple									=np.array(lowerCamelCase__       )
									assert isinstance(lowerCamelCase__				,    np.ndarray       )
									__UpperCamelCase :   Dict									=np.prod(boxes[:, 2:] - boxes[:, :2]				,    axis=1       )
									__UpperCamelCase :   int									=np.argsort(-areas       ).tolist()
									__UpperCamelCase :   Optional[Any]									=boxes[sorted_idxs] if boxes is not None else None
									__UpperCamelCase :   List[Any]									=obj_ids[sorted_idxs] if obj_ids is not None else None
									__UpperCamelCase :   Tuple									=obj_scores[sorted_idxs] if obj_scores is not None else None
									__UpperCamelCase :   Dict									=attr_ids[sorted_idxs] if attr_ids is not None else None
									__UpperCamelCase :   Optional[Any]									=attr_scores[sorted_idxs] if attr_scores is not None else None

									__UpperCamelCase :   int									=[self._random_color(maximum=1       ) for _ in range(len(lowerCamelCase__       )       )]
									__UpperCamelCase :   Tuple									=[assigned_colors[idx] for idx in sorted_idxs]
									if obj_ids is not None:
														__UpperCamelCase :   str									=self._create_text_labels_attr(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )
														for i in range(len(lowerCamelCase__       )       ):
																			__UpperCamelCase :   Dict									=assigned_colors[i]
																			self.add_box(boxes[i]				,    lowerCamelCase__       )
																			self.draw_labels(labels[i]				,    boxes[i]				,    lowerCamelCase__       )


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase						,							__UpperCamelCase						,							__UpperCamelCase						,							__UpperCamelCase :   Dict									=box
									__UpperCamelCase :   str									=(xa, ya)
									__UpperCamelCase :   Optional[int]									=(ya - ya) * (xa - xa)
									__UpperCamelCase :   Optional[Any]									=_SMALL_OBJ * self.scale
									if instance_area < small or ya - ya < 40 * self.scale:
														if ya >= self.height - 5:
																			__UpperCamelCase :   str									=(xa, ya)
														else:
																			__UpperCamelCase :   str									=(xa, ya)

									__UpperCamelCase :   Tuple									=(ya - ya) / np.sqrt(self.height * self.width       )
									__UpperCamelCase :   List[Any]									=self._change_color_brightness(lowerCamelCase__				,    brightness_factor=0.7       )
									__UpperCamelCase :   Any									=np.clip((height_ratio - 0.02) / 0.08 + 1				,    1.2				,    2       )
									font_size *= 0.75 * self.font_size

									self.draw_text(
									    text=lowerCamelCase__				,    position=lowerCamelCase__				,    color=lowerCamelCase__				,    )


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__="g"				,    lowerCamelCase__="left"				,    ):




									"""simple docstring"""

									__UpperCamelCase :   int									=0
									__UpperCamelCase :   Optional[int]									=self.font_size
									__UpperCamelCase :   Optional[Any]									=np.maximum(list(mplc.to_rgb(lowerCamelCase__       )       )				,    0.2       )
									__UpperCamelCase :   int									=max(0.8				,    np.max(lowerCamelCase__       )       )
									__UpperCamelCase :   str									={
									    'facecolor': 'black',
									    'alpha': self.alpha,
									    'pad': self.pad,
									    'edgecolor': 'none',
									}
									__UpperCamelCase						,							__UpperCamelCase :   Union[str, Any]									=position
									self.ax.text(
									    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    size=font_size * self.scale				,    family='sans-serif'				,    bbox=lowerCamelCase__				,    verticalalignment='top'				,    horizontalalignment=lowerCamelCase__				,    color=lowerCamelCase__				,    zorder=10				,    rotation=lowerCamelCase__				,    )


				def  __lowercase				(					self				,    lowerCamelCase__=None       ):




									"""simple docstring"""

									if saveas is None:
														__UpperCamelCase :   Optional[int]									=self.saveas
									if saveas.lower().endswith('.jpg'       ) or saveas.lower().endswith('.png'       ):
														cva.imwrite(
														    lowerCamelCase__				,    self._get_buffer()[:, :, ::-1]				,    )
									else:
														self.fig.savefig(lowerCamelCase__       )


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[int]									=[self.idaobj[i] for i in classes]
									__UpperCamelCase :   str									=[self.idaattr[i] for i in attr_classes]
									__UpperCamelCase :   Any									=[
									    f'{label} {score:.2f} {attr} {attr_score:.2f}'
									    for label, score, attr, attr_score in zip(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )
									]
									return labels


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Tuple									=[self.idaobj[i] for i in classes]
									if scores is not None:
														if labels is None:
																			__UpperCamelCase :   List[str]									=['{:.0f}%'.format(s * 100       ) for s in scores]
														else:
																			__UpperCamelCase :   Union[str, Any]									=['{} {:.0f}%'.format(lowerCamelCase__				,    s * 100       ) for li, s in zip(lowerCamelCase__				,    lowerCamelCase__       )]
									return labels


				def  __lowercase				(					self				,    lowerCamelCase__=255       ):




									"""simple docstring"""

									__UpperCamelCase :   Any									=np.random.randint(0				,    len(_COLORS       )       )
									__UpperCamelCase :   List[str]									=_COLORS[idx] * maximum
									if not self.rgb:
														__UpperCamelCase :   Optional[Any]									=ret[::-1]
									return ret


				def  __lowercase				(					self       ):




									"""simple docstring"""

									if not self.pynb:
														__UpperCamelCase						,							__UpperCamelCase :   Tuple									=self.canvas.print_to_buffer()
														if (width, height) != (self.width, self.height):
																			__UpperCamelCase :   Optional[int]									=cva.resize(self.img				,    (width, height)       )
														else:
																			__UpperCamelCase :   Tuple									=self.img
									else:
														__UpperCamelCase :   Optional[int]									=io.BytesIO()  # works for cairo backend
														self.canvas.print_rgba(lowerCamelCase__       )
														__UpperCamelCase						,							__UpperCamelCase :   int									=self.width, self.height
														__UpperCamelCase :   Union[str, Any]									=buf.getvalue()
														__UpperCamelCase :   Dict									=self.img

									__UpperCamelCase :   Dict									=np.frombuffer(lowerCamelCase__				,    dtype='uint8'       )
									__UpperCamelCase :   List[str]									=buffer.reshape(lowerCamelCase__				,    lowerCamelCase__				,    4       )
									__UpperCamelCase						,							__UpperCamelCase :   Union[str, Any]									=np.split(lowerCamelCase__				,    [3]				,    axis=2       )

									try:
														import numexpr as ne  # fuse them with numexpr

														__UpperCamelCase :   List[Any]									=ne.evaluate('img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)'       )
									except ImportError:
														__UpperCamelCase :   int									=alpha.astype('float32'       ) / 255.0
														__UpperCamelCase :   Tuple									=img * (1 - alpha) + rgb * alpha

									return visualized_image.astype('uint8'       )







				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									assert brightness_factor >= -1.0 and brightness_factor <= 1.0
									__UpperCamelCase :   List[Any]									=mplc.to_rgb(lowerCamelCase__       )
									__UpperCamelCase :   Dict									=colorsys.rgb_to_hls(*mplc.to_rgb(lowerCamelCase__       )       )
									__UpperCamelCase :   Dict									=polygon_color[1] + (brightness_factor * polygon_color[1])
									__UpperCamelCase :   Tuple									=0.0 if modified_lightness < 0.0 else modified_lightness
									__UpperCamelCase :   str									=1.0 if modified_lightness > 1.0 else modified_lightness
									__UpperCamelCase :   Union[str, Any]									=colorsys.hls_to_rgb(polygon_color[0]				,    lowerCamelCase__				,    polygon_color[2]       )
									return modified_color
A_			:Union[str, Any]	    =		(
    np.array(
        [
            0.000,
            0.447,
            0.741,
            0.850,
            0.325,
            0.098,
            0.929,
            0.694,
            0.125,
            0.494,
            0.184,
            0.556,
            0.466,
            0.674,
            0.188,
            0.301,
            0.745,
            0.933,
            0.635,
            0.078,
            0.184,
            0.300,
            0.300,
            0.300,
            0.600,
            0.600,
            0.600,
            1.000,
            0.000,
            0.000,
            1.000,
            0.500,
            0.000,
            0.749,
            0.749,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            1.000,
            0.667,
            0.000,
            1.000,
            0.333,
            0.333,
            0.000,
            0.333,
            0.667,
            0.000,
            0.333,
            1.000,
            0.000,
            0.667,
            0.333,
            0.000,
            0.667,
            0.667,
            0.000,
            0.667,
            1.000,
            0.000,
            1.000,
            0.333,
            0.000,
            1.000,
            0.667,
            0.000,
            1.000,
            1.000,
            0.000,
            0.000,
            0.333,
            0.500,
            0.000,
            0.667,
            0.500,
            0.000,
            1.000,
            0.500,
            0.333,
            0.000,
            0.500,
            0.333,
            0.333,
            0.500,
            0.333,
            0.667,
            0.500,
            0.333,
            1.000,
            0.500,
            0.667,
            0.000,
            0.500,
            0.667,
            0.333,
            0.500,
            0.667,
            0.667,
            0.500,
            0.667,
            1.000,
            0.500,
            1.000,
            0.000,
            0.500,
            1.000,
            0.333,
            0.500,
            1.000,
            0.667,
            0.500,
            1.000,
            1.000,
            0.500,
            0.000,
            0.333,
            1.000,
            0.000,
            0.667,
            1.000,
            0.000,
            1.000,
            1.000,
            0.333,
            0.000,
            1.000,
            0.333,
            0.333,
            1.000,
            0.333,
            0.667,
            1.000,
            0.333,
            1.000,
            1.000,
            0.667,
            0.000,
            1.000,
            0.667,
            0.333,
            1.000,
            0.667,
            0.667,
            1.000,
            0.667,
            1.000,
            1.000,
            1.000,
            0.000,
            1.000,
            1.000,
            0.333,
            1.000,
            1.000,
            0.667,
            1.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.167,
            0.000,
            0.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.167,
            0.000,
            0.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.143,
            0.143,
            0.143,
            0.857,
            0.857,
            0.857,
            1.000,
            1.000,
            1.000,
        ]
    )
    .astype(np.floataa)
    .reshape(-1, 3)
)

