




import io
import math
from typing import Dict, Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    get_image_size,
    infer_channel_dimension_format,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_vision_available, logging
from ...utils.import_utils import requires_backends


if is_vision_available():
			import textwrap

			from PIL import Image, ImageDraw, ImageFont

if is_torch_available():
			import torch

			from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
			__SCREAMING_SNAKE_CASE 						=False


__SCREAMING_SNAKE_CASE 						=logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE 						="""ybelkada/fonts"""

def 			a   ():
							if is_torch_available() and not is_torch_greater_or_equal_than_1_11:
														raise ImportError(
														    F"You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use "
														    '''Pix2StructImageProcessor. Please upgrade torch.'''     )

def 			a   (_lowerCAmelCase  ,    _lowerCAmelCase  ,    _lowerCAmelCase     ):
							requires_backends(_lowerCAmelCase  ,    ['''torch''']     )
							_check_torch_version()

							SCREAMING_SNAKE_CASE_   	=    image_tensor.unsqueeze(0     )
							SCREAMING_SNAKE_CASE_   	=    torch.nn.functional.unfold(_lowerCAmelCase  ,    (patch_height, patch_width)  ,    stride=(patch_height, patch_width)     )
							SCREAMING_SNAKE_CASE_   	=    patches.reshape(image_tensor.size(0     )  ,    image_tensor.size(1     )  ,    _lowerCAmelCase  ,    _lowerCAmelCase  ,    -1     )
							SCREAMING_SNAKE_CASE_   	=    patches.permute(0  ,    4  ,    2  ,    3  ,    1     ).reshape(
							    image_tensor.size(2     ) // patch_height  ,    image_tensor.size(3     ) // patch_width  ,    image_tensor.size(1     ) * patch_height * patch_width  ,    )
							return patches.unsqueeze(0     )

def 			a   (_lowerCAmelCase  ,    _lowerCAmelCase = 3_6  ,    _lowerCAmelCase = "black"  ,    _lowerCAmelCase = "white"  ,    _lowerCAmelCase = 5  ,    _lowerCAmelCase = 5  ,    _lowerCAmelCase = 5  ,    _lowerCAmelCase = 5  ,    _lowerCAmelCase = None  ,    _lowerCAmelCase = None  ,    ):
							requires_backends(_lowerCAmelCase  ,    '''vision'''     )
							# Add new lines so that each line is no more than 80 characters.

							SCREAMING_SNAKE_CASE_   	=    textwrap.TextWrapper(width=8_0     )
							SCREAMING_SNAKE_CASE_   	=    wrapper.wrap(text=_lowerCAmelCase     )
							SCREAMING_SNAKE_CASE_   	=    '''\n'''.join(_lowerCAmelCase     )

							if font_bytes is not None and font_path is None:
														SCREAMING_SNAKE_CASE_   	=    io.BytesIO(_lowerCAmelCase     )
							elif font_path is not None:
														SCREAMING_SNAKE_CASE_   	=    font_path
							else:
														SCREAMING_SNAKE_CASE_   	=    hf_hub_download(_lowerCAmelCase  ,    '''Arial.TTF'''     )
							SCREAMING_SNAKE_CASE_   	=    ImageFont.truetype(_lowerCAmelCase  ,    encoding='''UTF-8'''  ,    size=_lowerCAmelCase     )

							# Use a temporary canvas to determine the width and height in pixels when
							# rendering the text.
							SCREAMING_SNAKE_CASE_   	=    ImageDraw.Draw(Image.new('''RGB'''  ,    (1, 1)  ,    _lowerCAmelCase     )     )
							SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    temp_draw.textbbox((0, 0)  ,    _lowerCAmelCase  ,    _lowerCAmelCase     )

							# Create the actual image with a bit of padding around the text.
							SCREAMING_SNAKE_CASE_   	=    text_width + left_padding + right_padding
							SCREAMING_SNAKE_CASE_   	=    text_height + top_padding + bottom_padding
							SCREAMING_SNAKE_CASE_   	=    Image.new('''RGB'''  ,    (image_width, image_height)  ,    _lowerCAmelCase     )
							SCREAMING_SNAKE_CASE_   	=    ImageDraw.Draw(_lowerCAmelCase     )
							draw.text(xy=(left_padding, top_padding)  ,    text=_lowerCAmelCase  ,    fill=_lowerCAmelCase  ,    font=_lowerCAmelCase     )
							return image

def 			a   (_lowerCAmelCase  ,    _lowerCAmelCase  ,    **_lowerCAmelCase     ):
							requires_backends(_lowerCAmelCase  ,    '''vision'''     )

							# Convert to PIL image if necessary
							SCREAMING_SNAKE_CASE_   	=    to_pil_image(_lowerCAmelCase     )

							SCREAMING_SNAKE_CASE_   	=    render_text(_lowerCAmelCase  ,    **_lowerCAmelCase     )
							SCREAMING_SNAKE_CASE_   	=    max(header_image.width  ,    image.width     )

							SCREAMING_SNAKE_CASE_   	=    int(image.height * (new_width / image.width)     )
							SCREAMING_SNAKE_CASE_   	=    int(header_image.height * (new_width / header_image.width)     )

							SCREAMING_SNAKE_CASE_   	=    Image.new('''RGB'''  ,    (new_width, new_height + new_header_height)  ,    '''white'''     )
							new_image.paste(header_image.resize((new_width, new_header_height)     )  ,    (0, 0)     )
							new_image.paste(image.resize((new_width, new_height)     )  ,    (0, new_header_height)     )

							# Convert back to the original framework if necessary
							SCREAMING_SNAKE_CASE_   	=    to_numpy_array(_lowerCAmelCase     )

							if infer_channel_dimension_format(_lowerCAmelCase     ) == ChannelDimension.LAST:
														SCREAMING_SNAKE_CASE_   	=    to_channel_dimension_format(_lowerCAmelCase  ,    ChannelDimension.LAST     )

							return new_image






class  __magic_name__						(  __UpperCAmelCase):
				'''simple docstring'''







				SCREAMING_SNAKE_CASE__					:							List[Any]	      =					["flattened_patches"]


				def __init__(							self:   str		,					_lowerCamelCase:   bool = True		,					_lowerCamelCase:   bool = True		,					_lowerCamelCase:   Dict[str, int] = None		,					_lowerCamelCase:   int = 20_48		,					_lowerCamelCase:   bool = False		,					**_lowerCamelCase:   int		,					):
											super().__init__(**_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}
											SCREAMING_SNAKE_CASE_   	=    do_normalize
											SCREAMING_SNAKE_CASE_   	=    do_convert_rgb
											SCREAMING_SNAKE_CASE_   	=    max_patches
											SCREAMING_SNAKE_CASE_   	=    is_vqa


				def     _A							(							self:   Dict		,					_lowerCamelCase:   np.ndarray		,					_lowerCamelCase:   int		,					_lowerCamelCase:   dict		,					**_lowerCamelCase:   Union[str, Any]		):
											requires_backends(self.extract_flattened_patches		,					'''torch'''		)
											_check_torch_version()

											# convert to torch
											SCREAMING_SNAKE_CASE_   	=    to_channel_dimension_format(_lowerCamelCase		,					ChannelDimension.FIRST		)
											SCREAMING_SNAKE_CASE_   	=    torch.from_numpy(_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    patch_size['''height'''], patch_size['''width''']
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    get_image_size(_lowerCamelCase		)

											# maximize scale s.t.
											SCREAMING_SNAKE_CASE_   	=    math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width)		)
											SCREAMING_SNAKE_CASE_   	=    max(min(math.floor(scale * image_height / patch_height		)		,					_lowerCamelCase		)		,					1		)
											SCREAMING_SNAKE_CASE_   	=    max(min(math.floor(scale * image_width / patch_width		)		,					_lowerCamelCase		)		,					1		)
											SCREAMING_SNAKE_CASE_   	=    max(num_feasible_rows * patch_height		,					1		)
											SCREAMING_SNAKE_CASE_   	=    max(num_feasible_cols * patch_width		,					1		)

											SCREAMING_SNAKE_CASE_   	=    torch.nn.functional.interpolate(
											    image.unsqueeze(0		)		,					size=(resized_height, resized_width)		,					mode='''bilinear'''		,					align_corners=_lowerCamelCase		,					antialias=_lowerCamelCase		,					).squeeze(0		)

											# [1, rows, columns, patch_height * patch_width * image_channels]
											SCREAMING_SNAKE_CASE_   	=    torch_extract_patches(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    patches.shape
											SCREAMING_SNAKE_CASE_   	=    patches_shape[1]
											SCREAMING_SNAKE_CASE_   	=    patches_shape[2]
											SCREAMING_SNAKE_CASE_   	=    patches_shape[3]

											# [rows * columns, patch_height * patch_width * image_channels]
											SCREAMING_SNAKE_CASE_   	=    patches.reshape([rows * columns, depth]		)

											# [rows * columns, 1]
											SCREAMING_SNAKE_CASE_   	=    torch.arange(_lowerCamelCase		).reshape([rows, 1]		).repeat(1		,					_lowerCamelCase		).reshape([rows * columns, 1]		)
											SCREAMING_SNAKE_CASE_   	=    torch.arange(_lowerCamelCase		).reshape([1, columns]		).repeat(_lowerCamelCase		,					1		).reshape([rows * columns, 1]		)

											# Offset by 1 so the ids do not contain zeros, which represent padding.
											row_ids += 1
											col_ids += 1

											# Prepare additional patch features.
											# [rows * columns, 1]
											SCREAMING_SNAKE_CASE_   	=    row_ids.to(torch.floataa		)
											SCREAMING_SNAKE_CASE_   	=    col_ids.to(torch.floataa		)

											# [rows * columns, 2 + patch_height * patch_width * image_channels]
											SCREAMING_SNAKE_CASE_   	=    torch.cat([row_ids, col_ids, patches]		,					-1		)

											# [max_patches, 2 + patch_height * patch_width * image_channels]
											SCREAMING_SNAKE_CASE_   	=    torch.nn.functional.pad(_lowerCamelCase		,					[0, 0, 0, max_patches - (rows * columns)]		).float()

											SCREAMING_SNAKE_CASE_   	=    to_numpy_array(_lowerCamelCase		)

											return result


				def     _A							(							self:   Any		,					_lowerCamelCase:   np.ndarray		,					_lowerCamelCase:   Optional[Union[str, ChannelDimension]] = None		,					**_lowerCamelCase:   str		):
											if image.dtype == np.uinta:
																		SCREAMING_SNAKE_CASE_   	=    image.astype(np.floataa		)

											# take mean across the whole `image`
											SCREAMING_SNAKE_CASE_   	=    np.mean(_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    np.std(_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    max(_lowerCamelCase		,					1.0 / math.sqrt(np.prod(image.shape		)		)		)

											return normalize(_lowerCamelCase		,					mean=_lowerCamelCase		,					std=_lowerCamelCase		,					**_lowerCamelCase		)





				def     _A							(							self:   int		,					_lowerCamelCase:   ImageInput		,					_lowerCamelCase:   Optional[str] = None		,					_lowerCamelCase:   bool = None		,					_lowerCamelCase:   Optional[bool] = None		,					_lowerCamelCase:   Optional[int] = None		,					_lowerCamelCase:   Optional[Dict[str, int]] = None		,					_lowerCamelCase:   Optional[Union[str, TensorType]] = None		,					_lowerCamelCase:   ChannelDimension = ChannelDimension.FIRST		,					**_lowerCamelCase:   int		,					):
											SCREAMING_SNAKE_CASE_   	=    do_normalize if do_normalize is not None else self.do_normalize
											SCREAMING_SNAKE_CASE_   	=    do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
											SCREAMING_SNAKE_CASE_   	=    patch_size if patch_size is not None else self.patch_size
											SCREAMING_SNAKE_CASE_   	=    max_patches if max_patches is not None else self.max_patches
											SCREAMING_SNAKE_CASE_   	=    self.is_vqa

											if kwargs.get('''data_format'''		,					_lowerCamelCase		) is not None:
																		raise ValueError('''data_format is not an accepted input as the outputs are '''		)

											SCREAMING_SNAKE_CASE_   	=    make_list_of_images(_lowerCamelCase		)

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

											# PIL RGBA images are converted to RGB
											if do_convert_rgb:
																		SCREAMING_SNAKE_CASE_   	=    [convert_to_rgb(_lowerCamelCase		) for image in images]

											# All transformations expect numpy arrays.
											SCREAMING_SNAKE_CASE_   	=    [to_numpy_array(_lowerCamelCase		) for image in images]

											if is_vqa:
																		if header_text is None:
																									raise ValueError('''A header text must be provided for VQA models.'''		)
																		SCREAMING_SNAKE_CASE_   	=    kwargs.pop('''font_bytes'''		,					_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    kwargs.pop('''font_path'''		,					_lowerCamelCase		)

																		if isinstance(_lowerCamelCase		,					_lowerCamelCase		):
																									SCREAMING_SNAKE_CASE_   	=    [header_text] * len(_lowerCamelCase		)

																		SCREAMING_SNAKE_CASE_   	=    [
																		    render_header(_lowerCamelCase		,					header_text[i]		,					font_bytes=_lowerCamelCase		,					font_path=_lowerCamelCase		)
																		    for i, image in enumerate(_lowerCamelCase		)
																		]

											if do_normalize:
																		SCREAMING_SNAKE_CASE_   	=    [self.normalize(image=_lowerCamelCase		) for image in images]

											# convert to torch tensor and permute
											SCREAMING_SNAKE_CASE_   	=    [
											    self.extract_flattened_patches(image=_lowerCamelCase		,					max_patches=_lowerCamelCase		,					patch_size=_lowerCamelCase		)
											    for image in images
											]

											# create attention mask in numpy
											SCREAMING_SNAKE_CASE_   	=    [(image.sum(axis=-1		) != 0).astype(np.floataa		) for image in images]

											SCREAMING_SNAKE_CASE_   	=    BatchFeature(
											    data={'''flattened_patches''': images, '''attention_mask''': attention_masks}		,					tensor_type=_lowerCamelCase		)

											return encoded_outputs








import re
import string

import numpy as np

import datasets


__SCREAMING_SNAKE_CASE 						="""
Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.
"""

__SCREAMING_SNAKE_CASE 						="""
Args:
    predictions: List of predicted texts.
    references: List of reference texts.
    regexes_to_ignore: List, defaults to None. Regex expressions of characters to
        ignore when calculating the exact matches. Note: these regexes are removed
        from the input data before the changes based on the options below (e.g. ignore_case,
        ignore_punctuation, ignore_numbers) are applied.
    ignore_case: Boolean, defaults to False. If true, turns everything
        to lowercase so that capitalization differences are ignored.
    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
Returns:
    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.
Examples:
    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results[\"exact_match\"], 1))
    25.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results[\"exact_match\"], 1))
    50.0


    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results[\"exact_match\"], 1))
    75.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)
    >>> print(round(results[\"exact_match\"], 1))
    100.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]
    >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results[\"exact_match\"], 1))
    33.3

"""

__SCREAMING_SNAKE_CASE 						="""
"""






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







				def     _A							(							self:   Optional[int]		):
											return datasets.MetricInfo(
											    description=_DESCRIPTION		,					citation=_CITATION		,					inputs_description=_KWARGS_DESCRIPTION		,					features=datasets.Features(
											        {
											            '''predictions''': datasets.Value('''string'''		,					id='''sequence'''		),
											            '''references''': datasets.Value('''string'''		,					id='''sequence'''		),
											        }		)		,					reference_urls=[]		,					)





				def     _A							(							self:   Tuple		,					_lowerCamelCase:   int		,					_lowerCamelCase:   int		,					_lowerCamelCase:   Tuple=None		,					_lowerCamelCase:   str=False		,					_lowerCamelCase:   List[str]=False		,					_lowerCamelCase:   List[str]=False		,					):
											if regexes_to_ignore is not None:
																		for s in regexes_to_ignore:
																									SCREAMING_SNAKE_CASE_   	=    np.array([re.sub(_lowerCamelCase		,					''''''		,					_lowerCamelCase		) for x in predictions]		)
																									SCREAMING_SNAKE_CASE_   	=    np.array([re.sub(_lowerCamelCase		,					''''''		,					_lowerCamelCase		) for x in references]		)
											else:
																		SCREAMING_SNAKE_CASE_   	=    np.asarray(_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    np.asarray(_lowerCamelCase		)

											if ignore_case:
																		SCREAMING_SNAKE_CASE_   	=    np.char.lower(_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    np.char.lower(_lowerCamelCase		)

											if ignore_punctuation:
																		SCREAMING_SNAKE_CASE_   	=    string.punctuation.maketrans(''''''		,					''''''		,					string.punctuation		)
																		SCREAMING_SNAKE_CASE_   	=    np.char.translate(_lowerCamelCase		,					table=_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    np.char.translate(_lowerCamelCase		,					table=_lowerCamelCase		)

											if ignore_numbers:
																		SCREAMING_SNAKE_CASE_   	=    string.digits.maketrans(''''''		,					''''''		,					string.digits		)
																		SCREAMING_SNAKE_CASE_   	=    np.char.translate(_lowerCamelCase		,					table=_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    np.char.translate(_lowerCamelCase		,					table=_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    predictions == references

											return {"exact_match": np.mean(_lowerCamelCase		) * 1_00}


