





import tempfile
import unittest

import numpy as np
import torch

from diffusers import DiffusionPipeline
from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor




class 			_lowerCamelCase	(      unittest.TestCase      ):



      """simple docstring"""






      def   UpperCAmelCase						(	self			,  UpperCAmelCase = False				)    ->				Optional[Any]:






        '''simple docstring'''






        __snake_case				:			Optional[int]            =    10

        if only_cross_attention:
          __snake_case				:			Tuple            =    12
        else:
          # when only cross attention is not set, the cross attention dim must be the same as the query dim
          __snake_case				:			str            =    query_dim

        return {
            "query_dim": query_dim,
            "cross_attention_dim": cross_attention_dim,
            "heads": 2,
            "dim_head": 4,
            "added_kv_proj_dim": 6,
            "norm_num_groups": 1,
            "only_cross_attention": only_cross_attention,
            "processor": AttnAddedKVProcessor(),
        }







      def   UpperCAmelCase						(	self			,  UpperCAmelCase			,  UpperCAmelCase				)    ->				int:






        '''simple docstring'''






        __snake_case				:			Dict            =    2

        __snake_case				:			List[str]            =    torch.rand(UpperCAmelCase			,  UpperCAmelCase			,  3			,  2				)
        __snake_case				:			List[str]            =    torch.rand(UpperCAmelCase			,  4			,  UpperCAmelCase				)
        __snake_case				:			Optional[int]            =    None

        return {
            "hidden_states": hidden_states,
            "encoder_hidden_states": encoder_hidden_states,
            "attention_mask": attention_mask,
        }







      def   UpperCAmelCase						(	self				)    ->				Union[str, Any]:






        '''simple docstring'''






        torch.manual_seed(0				)

        __snake_case				:			Optional[int]            =    self.get_constructor_arguments(only_cross_attention=UpperCAmelCase				)
        __snake_case				:			int            =    Attention(**UpperCAmelCase				)

        self.assertTrue(attn.to_k is not None				)
        self.assertTrue(attn.to_v is not None				)

        __snake_case				:			Dict            =    self.get_forward_arguments(
            query_dim=constructor_args["query_dim"]			,  added_kv_proj_dim=constructor_args["added_kv_proj_dim"]				)

        __snake_case				:			Dict            =    attn(**UpperCAmelCase				)

        # only self attention

        torch.manual_seed(0				)

        __snake_case				:			Union[str, Any]            =    self.get_constructor_arguments(only_cross_attention=UpperCAmelCase				)
        __snake_case				:			int            =    Attention(**UpperCAmelCase				)

        self.assertTrue(attn.to_k is None				)
        self.assertTrue(attn.to_v is None				)

        __snake_case				:			Tuple            =    self.get_forward_arguments(
            query_dim=constructor_args["query_dim"]			,  added_kv_proj_dim=constructor_args["added_kv_proj_dim"]				)

        __snake_case				:			Any            =    attn(**UpperCAmelCase				)

        self.assertTrue((only_cross_attn_out != self_and_cross_attn_out).all()				)




class 			_lowerCamelCase	(      unittest.TestCase      ):



      """simple docstring"""






      def   UpperCAmelCase						(	self				)    ->				List[str]:






        '''simple docstring'''






        __snake_case				:			List[Any]            =    DiffusionPipeline.from_pretrained("hf-internal-testing/tiny-stable-diffusion-pipe"			,  safety_checker=UpperCAmelCase				)

        __snake_case				:			int            =    pipe(
            "foo"			,  num_inference_steps=2			,  generator=torch.Generator("cpu"				).manual_seed(0				)			,  output_type="np"			,  ).images

        # the initial conversion succeeds
        __snake_case				:			Dict            =    DiffusionPipeline.from_pretrained(
            "hf-internal-testing/tiny-stable-diffusion-pipe"			,  device_map="sequential"			,  safety_checker=UpperCAmelCase				)

        __snake_case				:			Optional[Any]            =    pipe(
            "foo"			,  num_inference_steps=2			,  generator=torch.Generator("cpu"				).manual_seed(0				)			,  output_type="np"			,  ).images

        with tempfile.TemporaryDirectory() as tmpdir:
          # save the converted model
          pipe.save_pretrained(UpperCAmelCase				)

          # can also load the converted weights
          __snake_case				:			Optional[int]            =    DiffusionPipeline.from_pretrained(UpperCAmelCase			,  device_map="sequential"			,  safety_checker=UpperCAmelCase				)

        __snake_case				:			Dict            =    pipe(
            "foo"			,  num_inference_steps=2			,  generator=torch.Generator("cpu"				).manual_seed(0				)			,  output_type="np"			,  ).images

        self.assertTrue(np.allclose(UpperCAmelCase			,  UpperCAmelCase			,  atol=1E-5				)				)
        self.assertTrue(np.allclose(UpperCAmelCase			,  UpperCAmelCase			,  atol=1E-5				)				)








import numpy as np
from cva import destroyAllWindows, imread, imshow, waitKey




class 			_lowerCamelCase	:



      """simple docstring"""






      def __init__(	self			,  UpperCAmelCase			,  UpperCAmelCase				)    ->				str:






        '''simple docstring'''






        __snake_case				:			int            =    0
        # max greyscale value for #FFFFFF
        __snake_case				:			int            =    int(self.get_greyscale(255			,  255			,  255				)				)

        if not self.min_threshold < threshold < self.max_threshold:
          __snake_case				:			Tuple            =    F"""Factor value should be from 0 to {self.max_threshold}"""
          raise ValueError(UpperCAmelCase				)

        __snake_case				:			List[Any]            =    input_img
        __snake_case				:			Any            =    threshold
        __snake_case      ,				__snake_case				:			str            =    self.input_img.shape[1], self.input_img.shape[0]

        # error table size (+4 columns and +1 row) greater than input image because of
        # lack of if statements
        __snake_case				:			Dict            =    [
            [0 for _ in range(self.height + 4				)] for __ in range(self.width + 1				)
        ]
        __snake_case				:			str            =    np.ones((self.width, self.height, 3)			,  np.uinta				) * 255







      @classmethod
      def   UpperCAmelCase						(	cls			,  UpperCAmelCase			,  UpperCAmelCase			,  UpperCAmelCase				)    ->				float:






        '''simple docstring'''






        return 0.114 * blue + 0.587 * green + 0.2_126 * red







      def   UpperCAmelCase						(	self				)    ->				None:






        '''simple docstring'''






        for y in range(self.height				):
          for x in range(self.width				):
            __snake_case				:			Optional[int]            =    int(self.get_greyscale(*self.input_img[y][x]				)				)
            if self.threshold > greyscale + self.error_table[y][x]:
              __snake_case				:			Any            =    (0, 0, 0)
              __snake_case				:			Optional[int]            =    greyscale + self.error_table[x][y]
            else:
              __snake_case				:			str            =    (255, 255, 255)
              __snake_case				:			Dict            =    greyscale + self.error_table[x][y] - 255
            self.error_table[y][x + 1] += int(8 / 32 * current_error				)
            self.error_table[y][x + 2] += int(4 / 32 * current_error				)
            self.error_table[y + 1][x] += int(8 / 32 * current_error				)
            self.error_table[y + 1][x + 1] += int(4 / 32 * current_error				)
            self.error_table[y + 1][x + 2] += int(2 / 32 * current_error				)
            self.error_table[y + 1][x - 1] += int(4 / 32 * current_error				)
            self.error_table[y + 1][x - 2] += int(2 / 32 * current_error				)


if __name__ == "__main__":
     # create Burke's instances with original images in greyscale
     _UpperCamelCase    =	[
         Burkes(imread('''image_data/lena.jpg''', 1), threshold)
         for threshold in (1, 126, 130, 140)
     ]

     for burkes in burkes_instances:
          burkes.process()

     for burkes in burkes_instances:
          imshow(
              F'''Original image with dithering threshold: {burkes.threshold}''',
              burkes.output_img,
          )

     waitKey(0)
     destroyAllWindows()

