





"""simple docstring"""



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:
       a_					=     False


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







def 						__lowercase	(  )  ->int:



    '''simple docstring'''







    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 						__lowercase	(  snake_case_    :    int							,snake_case_    :    Dict							,snake_case_    :    int		)  ->Any:



    '''simple docstring'''







    requires_backends(snake_case_							,['''torch''']		)
    _check_torch_version()

    __A       :		str							=	image_tensor.unsqueeze(0		)
    __A       :		Dict							=	torch.nn.functional.unfold(snake_case_							,(patch_height, patch_width)							,stride=(patch_height, patch_width)		)
    __A       :		str							=	patches.reshape(image_tensor.size(0		)							,image_tensor.size(1		)							,snake_case_							,snake_case_							,-1		)
    __A       :		Optional[int]							=	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 						__lowercase	(  snake_case_    :    str							,snake_case_    :    int = 36							,snake_case_    :    str = "black"							,snake_case_    :    str = "white"							,snake_case_    :    int = 5							,snake_case_    :    int = 5							,snake_case_    :    int = 5							,snake_case_    :    int = 5							,snake_case_    :    Optional[bytes] = None							,snake_case_    :    Optional[str] = None							,)  ->Image.Image:



    '''simple docstring'''







    requires_backends(snake_case_							,'''vision'''		)
    # Add new lines so that each line is no more than 80 characters.

    __A       :		Union[str, Any]							=	textwrap.TextWrapper(width=80		)
    __A       :		Union[str, Any]							=	wrapper.wrap(text=snake_case_		)
    __A       :		List[Any]							=	'''\n'''.join(snake_case_		)

    if font_bytes is not None and font_path is None:
        __A       :		Any							=	io.BytesIO(snake_case_		)
    elif font_path is not None:
        __A       :		Optional[Any]							=	font_path
    else:
        __A       :		List[str]							=	hf_hub_download(snake_case_							,'''Arial.TTF'''		)
    __A       :		Union[str, Any]							=	ImageFont.truetype(snake_case_							,encoding='''UTF-8'''							,size=snake_case_		)

    # Use a temporary canvas to determine the width and height in pixels when
    # rendering the text.
    __A       :		List[Any]							=	ImageDraw.Draw(Image.new('''RGB'''							,(1, 1)							,snake_case_		)		)
    __A					,			__A					,			__A					,			__A       :		List[Any]							=	temp_draw.textbbox((0, 0)							,snake_case_							,snake_case_		)

    # Create the actual image with a bit of padding around the text.
    __A       :		List[str]							=	text_width + left_padding + right_padding
    __A       :		Tuple							=	text_height + top_padding + bottom_padding
    __A       :		Tuple							=	Image.new('''RGB'''							,(image_width, image_height)							,snake_case_		)
    __A       :		Any							=	ImageDraw.Draw(snake_case_		)
    draw.text(xy=(left_padding, top_padding)							,text=snake_case_							,fill=snake_case_							,font=snake_case_		)
    return image







def 						__lowercase	(  snake_case_    :    np.ndarray							,snake_case_    :    str							,**snake_case_    :    Tuple		)  ->Optional[int]:



    '''simple docstring'''







    requires_backends(snake_case_							,'''vision'''		)

    # Convert to PIL image if necessary
    __A       :		int							=	to_pil_image(snake_case_		)

    __A       :		Optional[Any]							=	render_text(snake_case_							,**snake_case_		)
    __A       :		Tuple							=	max(header_image.width							,image.width		)

    __A       :		List[Any]							=	int(image.height * (new_width / image.width)		)
    __A       :		Optional[int]							=	int(header_image.height * (new_width / header_image.width)		)

    __A       :		Optional[int]							=	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
    __A       :		List[str]							=	to_numpy_array(snake_case_		)

    if infer_channel_dimension_format(snake_case_		) == ChannelDimension.LAST:
        __A       :		int							=	to_channel_dimension_format(snake_case_							,ChannelDimension.LAST		)

    return new_image






class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





 """simple docstring"""


 _lowerCamelCase								=	["""flattened_patches"""]

 def __init__(       self   ,		__lowerCamelCase = True   ,		__lowerCamelCase = True   ,		__lowerCamelCase = None   ,		__lowerCamelCase = 2048   ,		__lowerCamelCase = False   ,		**__lowerCamelCase   ,		):



     '''simple docstring'''




     super().__init__(**__lowerCamelCase    )
     __A       :		str							=	patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}
     __A       :		Optional[int]							=	do_normalize
     __A       :		str							=	do_convert_rgb
     __A       :		List[str]							=	max_patches
     __A       :		Optional[int]							=	is_vqa

 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		**__lowerCamelCase    ):



     '''simple docstring'''




     requires_backends(self.extract_flattened_patches   ,		'''torch'''    )
     _check_torch_version()

     # convert to torch
     __A       :		Any							=	to_channel_dimension_format(__lowerCamelCase   ,		ChannelDimension.FIRST    )
     __A       :		List[str]							=	torch.from_numpy(__lowerCamelCase    )

     __A					,			__A       :		Optional[Any]							=	patch_size['''height'''], patch_size['''width''']
     __A					,			__A       :		Tuple							=	get_image_size(__lowerCamelCase    )

     # maximize scale s.t.
     __A       :		Any							=	math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width)    )
     __A       :		str							=	max(min(math.floor(scale * image_height / patch_height    )   ,		__lowerCamelCase    )   ,		1    )
     __A       :		Optional[Any]							=	max(min(math.floor(scale * image_width / patch_width    )   ,		__lowerCamelCase    )   ,		1    )
     __A       :		List[str]							=	max(num_feasible_rows * patch_height   ,		1    )
     __A       :		List[Any]							=	max(num_feasible_cols * patch_width   ,		1    )

     __A       :		Dict							=	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]
     __A       :		Dict							=	torch_extract_patches(__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    )

     __A       :		str							=	patches.shape
     __A       :		int							=	patches_shape[1]
     __A       :		int							=	patches_shape[2]
     __A       :		List[Any]							=	patches_shape[3]

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

     # [rows * columns, 1]
     __A       :		List[Any]							=	torch.arange(__lowerCamelCase    ).reshape([rows, 1]    ).repeat(1   ,		__lowerCamelCase    ).reshape([rows * columns, 1]    )
     __A       :		Dict							=	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]
     __A       :		Union[str, Any]							=	row_ids.to(torch.floataa    )
     __A       :		List[str]							=	col_ids.to(torch.floataa    )

     # [rows * columns, 2 + patch_height * patch_width * image_channels]
     __A       :		Union[str, Any]							=	torch.cat([row_ids, col_ids, patches]   ,		-1    )

     # [max_patches, 2 + patch_height * patch_width * image_channels]
     __A       :		Optional[Any]							=	torch.nn.functional.pad(__lowerCamelCase   ,		[0, 0, 0, max_patches - (rows * columns)]    ).float()

     __A       :		int							=	to_numpy_array(__lowerCamelCase    )

     return result

 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase = None   ,		**__lowerCamelCase    ):



     '''simple docstring'''




     if image.dtype == np.uinta:
         __A       :		Tuple							=	image.astype(np.floataa    )

     # take mean across the whole `image`
     __A       :		Tuple							=	np.mean(__lowerCamelCase    )
     __A       :		Dict							=	np.std(__lowerCamelCase    )
     __A       :		Union[str, Any]							=	max(__lowerCamelCase   ,		1.0 / math.sqrt(np.prod(image.shape    )    )    )

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







 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase = None   ,		__lowerCamelCase = None   ,		__lowerCamelCase = None   ,		__lowerCamelCase = None   ,		__lowerCamelCase = None   ,		__lowerCamelCase = None   ,		__lowerCamelCase = ChannelDimension.FIRST   ,		**__lowerCamelCase   ,		):



     '''simple docstring'''




     __A       :		int							=	do_normalize if do_normalize is not None else self.do_normalize
     __A       :		List[str]							=	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
     __A       :		int							=	patch_size if patch_size is not None else self.patch_size
     __A       :		Optional[Any]							=	max_patches if max_patches is not None else self.max_patches
     __A       :		Any							=	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 '''    )

     __A       :		Any							=	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:
         __A       :		Dict							=	[convert_to_rgb(__lowerCamelCase    ) for image in images]

     # All transformations expect numpy arrays.
     __A       :		List[str]							=	[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.'''    )
         __A       :		Optional[Any]							=	kwargs.pop('''font_bytes'''   ,		__lowerCamelCase    )
         __A       :		Optional[int]							=	kwargs.pop('''font_path'''   ,		__lowerCamelCase    )

         if isinstance(__lowerCamelCase   ,		__lowerCamelCase    ):
             __A       :		List[str]							=	[header_text] * len(__lowerCamelCase    )

         __A       :		Dict							=	[
             render_header(__lowerCamelCase   ,		header_text[i]   ,		font_bytes=__lowerCamelCase   ,		font_path=__lowerCamelCase    )
             for i, image in enumerate(__lowerCamelCase    )
         ]

     if do_normalize:
         __A       :		Tuple							=	[self.normalize(image=__lowerCamelCase    ) for image in images]

     # convert to torch tensor and permute
     __A       :		List[str]							=	[
         self.extract_flattened_patches(image=__lowerCamelCase   ,		max_patches=__lowerCamelCase   ,		patch_size=__lowerCamelCase    )
         for image in images
     ]

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

     __A       :		List[str]							=	BatchFeature(
         data={'''flattened_patches''': images, '''attention_mask''': attention_masks}   ,		tensor_type=__lowerCamelCase    )

     return encoded_outputs











"""simple docstring"""



def 						__lowercase	(  snake_case_    :    int							,snake_case_    :    int		)  ->int:



    '''simple docstring'''







    return int((input_a, input_a).count(0		) == 0		)







def 						__lowercase	(  )  ->None:



    '''simple docstring'''







    assert and_gate(0							,0		) == 0
    assert and_gate(0							,1		) == 0
    assert and_gate(1							,0		) == 0
    assert and_gate(1							,1		) == 1


if __name__ == "__main__":
       test_and_gate()
       print(and_gate(1, 0))
       print(and_gate(0, 0))
       print(and_gate(0, 1))
       print(and_gate(1, 1))




