



'''simple docstring'''


import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
   import torch

   from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
   _lowerCamelCase      :			List[Any]       =      False

if is_vision_available():
   from PIL import Image

   from transformers import PixaStructImageProcessor

class 					SCREAMING_SNAKE_CASE					(    unittest.TestCase						):






    """simple docstring"""





    def __init__(    self :   int    ,		UpperCamelCase__ :   str    ,		UpperCamelCase__ :   List[str]=7    ,		UpperCamelCase__ :   Optional[int]=3    ,		UpperCamelCase__ :   Optional[Any]=1_8    ,		UpperCamelCase__ :   List[Any]=3_0    ,		UpperCamelCase__ :   List[Any]=4_0_0    ,		UpperCamelCase__ :   int=None    ,		UpperCamelCase__ :   int=True    ,		UpperCamelCase__ :   Tuple=True    ,		UpperCamelCase__ :   str=None    ,		):


       """simple docstring"""







       UpperCamelCase      							=    size if size is not None else {'height': 2_0, 'width': 2_0}
       UpperCamelCase      							=    parent
       UpperCamelCase      							=    batch_size
       UpperCamelCase      							=    num_channels
       UpperCamelCase      							=    image_size
       UpperCamelCase      							=    min_resolution
       UpperCamelCase      							=    max_resolution
       UpperCamelCase      							=    size
       UpperCamelCase      							=    do_normalize
       UpperCamelCase      							=    do_convert_rgb
       UpperCamelCase      							=    [5_1_2, 1_0_2_4, 2_0_4_8, 4_0_9_6]
       UpperCamelCase      							=    patch_size if patch_size is not None else {'height': 1_6, 'width': 1_6}






    def 					A			(    self :   Any					):


       """simple docstring"""







       return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}






    def 					A			(    self :   str					):


       """simple docstring"""







       UpperCamelCase      							=    'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
       UpperCamelCase      							=    Image.open(requests.get(lowercase_    ,		stream=lowercase_					).raw					).convert('RGB'					)
       return raw_image

@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11  ,		reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""  ,		)
@require_torch
@require_vision
class 					SCREAMING_SNAKE_CASE					(    lowercase__  ,		unittest.TestCase						):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE          =    PixaStructImageProcessor if is_vision_available() else None






    def 					A			(    self :   Any					):


       """simple docstring"""







       UpperCamelCase      							=    PixaStructImageProcessingTester(self					)






    @property
    def 					A			(    self :   List[str]					):


       """simple docstring"""







       return self.image_processor_tester.prepare_image_processor_dict()






    def 					A			(    self :   Union[str, Any]					):


       """simple docstring"""







       UpperCamelCase      							=    self.image_processing_class(**self.image_processor_dict					)
       self.assertTrue(hasattr(lowercase_    ,		'do_normalize'					)					)
       self.assertTrue(hasattr(lowercase_    ,		'do_convert_rgb'					)					)






    def 					A			(    self :   List[str]					):


       """simple docstring"""







       UpperCamelCase      							=    self.image_processor_tester.prepare_dummy_image()

       UpperCamelCase      							=    self.image_processing_class(**self.image_processor_dict					)
       UpperCamelCase      							=    2_0_4_8

       UpperCamelCase      							=    image_processor(lowercase_    ,		return_tensors='pt'    ,		max_patches=lowercase_					)
       self.assertTrue(torch.allclose(inputs.flattened_patches.mean()    ,		torch.tensor(0.0_6_0_6					)    ,		atol=1E-3    ,		rtol=1E-3					)					)






    def 					A			(    self :   int					):


       """simple docstring"""







       UpperCamelCase      							=    self.image_processing_class(**self.image_processor_dict					)
       # create random PIL images
       UpperCamelCase      							=    prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=lowercase_					)
       for image in image_inputs:
          self.assertIsInstance(lowercase_    ,		Image.Image					)

       # Test not batched input
       UpperCamelCase      							=    (
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
          # Test not batched input
          UpperCamelCase      							=    image_processor(
              image_inputs[0]    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(1, max_patch, expected_hidden_dim)    ,		)

          # Test batched
          UpperCamelCase      							=    image_processor(
              lowercase_    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)    ,		)






    def 					A			(    self :   Dict					):


       """simple docstring"""







       UpperCamelCase      							=    self.image_processing_class(**self.image_processor_dict					)
       # create random PIL images
       UpperCamelCase      							=    prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=lowercase_					)
       for image in image_inputs:
          self.assertIsInstance(lowercase_    ,		Image.Image					)

       # Test not batched input
       UpperCamelCase      							=    (
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       UpperCamelCase      							=    True

       for max_patch in self.image_processor_tester.max_patches:
          # Test not batched input
          with self.assertRaises(lowercase_					):
             UpperCamelCase      							=    image_processor(
                 image_inputs[0]    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches

          UpperCamelCase      							=    'Hello'

          UpperCamelCase      							=    image_processor(
              image_inputs[0]    ,		return_tensors='pt'    ,		max_patches=lowercase_    ,		header_text=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(1, max_patch, expected_hidden_dim)    ,		)

          # Test batched
          UpperCamelCase      							=    image_processor(
              lowercase_    ,		return_tensors='pt'    ,		max_patches=lowercase_    ,		header_text=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)    ,		)






    def 					A			(    self :   Optional[int]					):


       """simple docstring"""







       UpperCamelCase      							=    self.image_processing_class(**self.image_processor_dict					)
       # create random numpy tensors
       UpperCamelCase      							=    prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=lowercase_    ,		numpify=lowercase_					)
       for image in image_inputs:
          self.assertIsInstance(lowercase_    ,		np.ndarray					)

       UpperCamelCase      							=    (
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
          # Test not batched input
          UpperCamelCase      							=    image_processor(
              image_inputs[0]    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(1, max_patch, expected_hidden_dim)    ,		)

          # Test batched
          UpperCamelCase      							=    image_processor(
              lowercase_    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)    ,		)






    def 					A			(    self :   Union[str, Any]					):


       """simple docstring"""







       UpperCamelCase      							=    self.image_processing_class(**self.image_processor_dict					)
       # create random PyTorch tensors
       UpperCamelCase      							=    prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=lowercase_    ,		torchify=lowercase_					)
       for image in image_inputs:
          self.assertIsInstance(lowercase_    ,		torch.Tensor					)

       # Test not batched input
       UpperCamelCase      							=    (
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
          # Test not batched input
          UpperCamelCase      							=    image_processor(
              image_inputs[0]    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(1, max_patch, expected_hidden_dim)    ,		)

          # Test batched
          UpperCamelCase      							=    image_processor(
              lowercase_    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)    ,		)

@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11  ,		reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""  ,		)
@require_torch
@require_vision
class 					SCREAMING_SNAKE_CASE					(    lowercase__  ,		unittest.TestCase						):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE          =    PixaStructImageProcessor if is_vision_available() else None






    def 					A			(    self :   Tuple					):


       """simple docstring"""







       UpperCamelCase      							=    PixaStructImageProcessingTester(self    ,		num_channels=4					)
       UpperCamelCase      							=    3






    @property
    def 					A			(    self :   Optional[int]					):


       """simple docstring"""







       return self.image_processor_tester.prepare_image_processor_dict()






    def 					A			(    self :   Optional[Any]					):


       """simple docstring"""







       UpperCamelCase      							=    self.image_processing_class(**self.image_processor_dict					)
       self.assertTrue(hasattr(lowercase_    ,		'do_normalize'					)					)
       self.assertTrue(hasattr(lowercase_    ,		'do_convert_rgb'					)					)






    def 					A			(    self :   Union[str, Any]					):


       """simple docstring"""







       UpperCamelCase      							=    self.image_processing_class(**self.image_processor_dict					)
       # create random PIL images
       UpperCamelCase      							=    prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=lowercase_					)
       for image in image_inputs:
          self.assertIsInstance(lowercase_    ,		Image.Image					)

       # Test not batched input
       UpperCamelCase      							=    (
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * (self.image_processor_tester.num_channels - 1)
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
          # Test not batched input
          UpperCamelCase      							=    image_processor(
              image_inputs[0]    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(1, max_patch, expected_hidden_dim)    ,		)

          # Test batched
          UpperCamelCase      							=    image_processor(
              lowercase_    ,		return_tensors='pt'    ,		max_patches=lowercase_					).flattened_patches
          self.assertEqual(
              encoded_images.shape    ,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)    ,		)





from manim import *




class       lowercase_					(lowercase__   ):





				def 						__UpperCamelCase    (				self)  -> List[Any]:
											a__      =Rectangle(height=0.5       ,  width=0.5)
											a__      =Rectangle(height=0.46       ,  width=0.46).set_stroke(width=0)

											a__      =[mem.copy() for i in range(6)]
											a__      =[mem.copy() for i in range(6)]
											a__      =VGroup(*lowercase_).arrange(lowercase_       ,  buff=0)
											a__      =VGroup(*lowercase_).arrange(lowercase_       ,  buff=0)
											a__      =VGroup(lowercase_       ,  lowercase_).arrange(lowercase_       ,  buff=0)
											a__      =Text('CPU'       ,  font_size=24)
											a__      =Group(lowercase_       ,  lowercase_).arrange(lowercase_       ,  buff=0.5       ,  aligned_edge=lowercase_)
											cpu.move_to([-2.5, -0.5, 0])
											self.add(lowercase_)

											a__      =[mem.copy() for i in range(4)]
											a__      =VGroup(*lowercase_).arrange(lowercase_       ,  buff=0)
											a__      =Text('GPU'       ,  font_size=24)
											a__      =Group(lowercase_       ,  lowercase_).arrange(lowercase_       ,  buff=0.5       ,  aligned_edge=lowercase_)
											gpu.move_to([-1, -1, 0])
											self.add(lowercase_)

											a__      =[mem.copy() for i in range(6)]
											a__      =VGroup(*lowercase_).arrange(lowercase_       ,  buff=0)

											a__      =Text('Model'       ,  font_size=24)
											a__      =Group(lowercase_       ,  lowercase_).arrange(lowercase_       ,  buff=0.5       ,  aligned_edge=lowercase_)
											model.move_to([3, -1.0, 0])
											self.add(lowercase_)

											a__      =[]
											for i, rect in enumerate(lowercase_):
																		rect.set_stroke(lowercase_)
																		# target = fill.copy().set_fill(YELLOW, opacity=0.7)
																		# target.move_to(rect)
																		# self.add(target)

																		a__      =Rectangle(height=0.46 / 4       ,  width=0.46 / 3).set_stroke(width=0.0).set_fill(lowercase_       ,  opacity=0.7)

																		if i == 0:
																									cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT)       ,  buff=0.02       ,  direction=lowercase_)
																									cpu_target.set_x(cpu_target.get_x() + 0.1)
																		elif i == 3:
																									cpu_target.next_to(cpu_targs[0]       ,  direction=lowercase_       ,  buff=0.0)
																		else:
																									cpu_target.next_to(cpu_targs[i - 1]       ,  direction=lowercase_       ,  buff=0.0)
																		self.add(lowercase_)
																		cpu_targs.append(lowercase_)

											a__      =[mem.copy() for i in range(6)]
											a__      =VGroup(*lowercase_).arrange(lowercase_       ,  buff=0)

											a__      =Text('Loaded Checkpoint'       ,  font_size=24)
											a__      =Group(lowercase_       ,  lowercase_).arrange(lowercase_       ,  aligned_edge=lowercase_       ,  buff=0.4)
											checkpoint.move_to([3, 0.5, 0])

											a__      =Square(side_length=2.2)
											key.move_to([-5, 2, 0])

											a__      =MarkupText(
											    F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model"""       ,  font_size=18       ,  )

											key_text.move_to([-5, 2.4, 0])

											self.add(lowercase_       ,  lowercase_)

											a__      =MarkupText(
											    F"""<span fgcolor='{BLUE}'>●</span> Checkpoint"""       ,  font_size=18       ,  )

											blue_text.next_to(lowercase_       ,  DOWN * 2.4       ,  aligned_edge=key_text.get_left())

											a__      =MarkupText(
											    F"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>."""       ,  font_size=24       ,  )
											step_a.move_to([2, 2, 0])
											self.play(Write(lowercase_)       ,  Write(lowercase_))

											self.play(Write(lowercase_       ,  run_time=1)       ,  Create(lowercase_       ,  run_time=1))

											a__      =[]
											a__      =[]
											for i, rect in enumerate(lowercase_):
																		a__      =fill.copy().set_fill(lowercase_       ,  opacity=0.7)
																		target.move_to(lowercase_)
																		first_animations.append(GrowFromCenter(lowercase_       ,  run_time=1))

																		a__      =target.copy()
																		cpu_target.generate_target()
																		if i < 5:
																									cpu_target.target.move_to(cpu_left_col_base[i + 1])
																		else:
																									cpu_target.target.move_to(cpu_right_col_base[i - 5])
																		second_animations.append(MoveToTarget(lowercase_       ,  run_time=1.5))

											self.play(*lowercase_)
											self.play(*lowercase_)
											self.wait()

