
"""simple docstring"""


import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()







class 		lowerCamelCase__					(					unittest.TestCase				):





			'''simple docstring'''



			@property
			def 					_lowerCAmelCase		(							self  ) ->     Union[str, Any]:
				_lowerCAmelCase								=1
				_lowerCAmelCase								=3
				_lowerCAmelCase								=(32, 32)

				_lowerCAmelCase								=floats_tensor((batch_size, num_channels) + sizes     ,     rng=random.Random(0  )  ).to(__UpperCAmelCase  )
				return image



			@property
			def 					_lowerCAmelCase		(							self  ) ->     Optional[Any]:
				torch.manual_seed(0  )
				_lowerCAmelCase								=UNetaDModel(
				    block_out_channels=(32, 64)     ,     layers_per_block=2     ,     sample_size=32     ,     in_channels=6     ,     out_channels=3     ,     down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")     ,     up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")     ,     )
				return model



			@property
			def 					_lowerCAmelCase		(							self  ) ->     Dict:
				torch.manual_seed(0  )
				_lowerCAmelCase								=VQModel(
				    block_out_channels=[32, 64]     ,     in_channels=3     ,     out_channels=3     ,     down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]     ,     up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]     ,     latent_channels=3     ,     )
				return model



			def 					_lowerCAmelCase		(							self  ) ->     Tuple:
				_lowerCAmelCase								="""cpu"""
				_lowerCAmelCase								=self.dummy_uncond_unet
				_lowerCAmelCase								=DDIMScheduler()
				_lowerCAmelCase								=self.dummy_vq_model

				_lowerCAmelCase								=LDMSuperResolutionPipeline(unet=__UpperCAmelCase     ,     vqvae=__UpperCAmelCase     ,     scheduler=__UpperCAmelCase  )
				ldm.to(__UpperCAmelCase  )
				ldm.set_progress_bar_config(disable=__UpperCAmelCase  )

				_lowerCAmelCase								=self.dummy_image.to(__UpperCAmelCase  )

				_lowerCAmelCase								=torch.Generator(device=__UpperCAmelCase  ).manual_seed(0  )
				_lowerCAmelCase								=ldm(image=__UpperCAmelCase     ,     generator=__UpperCAmelCase     ,     num_inference_steps=2     ,     output_type="""numpy"""  ).images

				_lowerCAmelCase								=image[0, -3:, -3:, -1]

				assert image.shape == (1, 64, 64, 3)
				_lowerCAmelCase								=np.array([0.8_6_7_8, 0.8_2_4_5, 0.6_3_8_1, 0.6_8_3_0, 0.4_3_8_5, 0.5_5_9_9, 0.4_6_4_1, 0.6_2_0_1, 0.5_1_5_0]  )

				assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2



			@unittest.skipIf(torch_device != """cuda"""     ,     """This test requires a GPU"""  )
			def 					_lowerCAmelCase		(							self  ) ->     Union[str, Any]:
				_lowerCAmelCase								=self.dummy_uncond_unet
				_lowerCAmelCase								=DDIMScheduler()
				_lowerCAmelCase								=self.dummy_vq_model

				# put models in fp16
				_lowerCAmelCase								=unet.half()
				_lowerCAmelCase								=vqvae.half()

				_lowerCAmelCase								=LDMSuperResolutionPipeline(unet=__UpperCAmelCase     ,     vqvae=__UpperCAmelCase     ,     scheduler=__UpperCAmelCase  )
				ldm.to(__UpperCAmelCase  )
				ldm.set_progress_bar_config(disable=__UpperCAmelCase  )

				_lowerCAmelCase								=self.dummy_image.to(__UpperCAmelCase  )

				_lowerCAmelCase								=ldm(__UpperCAmelCase     ,     num_inference_steps=2     ,     output_type="""numpy"""  ).images

				assert image.shape == (1, 64, 64, 3)







@slow
@require_torch
class 		lowerCamelCase__					(					unittest.TestCase				):





			'''simple docstring'''



			def 					_lowerCAmelCase		(							self  ) ->     Union[str, Any]:
				_lowerCAmelCase								=load_image(
				    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
				    """/vq_diffusion/teddy_bear_pool.png"""  )
				_lowerCAmelCase								=init_image.resize((64, 64)     ,     resample=PIL_INTERPOLATION["""lanczos"""]  )

				_lowerCAmelCase								=LDMSuperResolutionPipeline.from_pretrained("""duongna/ldm-super-resolution"""     ,     device_map="""auto"""  )
				ldm.set_progress_bar_config(disable=__UpperCAmelCase  )

				_lowerCAmelCase								=torch.manual_seed(0  )
				_lowerCAmelCase								=ldm(image=__UpperCAmelCase     ,     generator=__UpperCAmelCase     ,     num_inference_steps=20     ,     output_type="""numpy"""  ).images

				_lowerCAmelCase								=image[0, -3:, -3:, -1]

				assert image.shape == (1, 2_56, 2_56, 3)
				_lowerCAmelCase								=np.array([0.7_6_4_4, 0.7_6_7_9, 0.7_6_4_2, 0.7_6_3_3, 0.7_6_6_6, 0.7_5_6_0, 0.7_4_2_5, 0.7_2_5_7, 0.6_9_0_7]  )

				assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2










import json
import os
import random
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
       from PIL import Image

       from transformers import FlavaImageProcessor, FlavaProcessor
       from transformers.models.flava.image_processing_flava import (
           FLAVA_CODEBOOK_MEAN,
           FLAVA_CODEBOOK_STD,
           FLAVA_IMAGE_MEAN,
           FLAVA_IMAGE_STD,
       )





@require_vision
class 	lowerCAmelCase__(       unittest.TestCase			):






       '''simple docstring'''


       def 			UpperCamelCase_	(					self							)	->   str:
            _SCREAMING_SNAKE_CASE				:		str  			=							tempfile.mkdtemp()

            # fmt: off
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"]
            # fmt: on
            _SCREAMING_SNAKE_CASE				:		int  			=							os.path.join(self.tmpdirname			,  VOCAB_FILES_NAMES["vocab_file"]							)

            with open(self.vocab_file			,  "w"			,  encoding="utf-8"							) as fp:
                 fp.write("".join([x + "\n" for x in vocab_tokens]							)							)

            _SCREAMING_SNAKE_CASE				:		Any  			=							{
                "image_mean": FLAVA_IMAGE_MEAN,
                "image_std": FLAVA_IMAGE_STD,
                "do_normalize": True,
                "do_resize": True,
                "size": 2_2_4,
                "do_center_crop": True,
                "crop_size": 2_2_4,
                "input_size_patches": 1_4,
                "total_mask_patches": 7_5,
                "mask_group_max_patches": None,
                "mask_group_min_patches": 1_6,
                "mask_group_min_aspect_ratio": 0.3,
                "mask_group_max_aspect_ratio": None,
                "codebook_do_resize": True,
                "codebook_size": 1_1_2,
                "codebook_do_center_crop": True,
                "codebook_crop_size": 1_1_2,
                "codebook_do_map_pixels": True,
                "codebook_do_normalize": True,
                "codebook_image_mean": FLAVA_CODEBOOK_MEAN,
                "codebook_image_std": FLAVA_CODEBOOK_STD,
            }

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							os.path.join(self.tmpdirname			,  __lowerCamelCase							)
            with open(self.image_processor_file			,  "w"			,  encoding="utf-8"							) as fp:
                 json.dump(__lowerCamelCase			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   List[str]:
            return BertTokenizer.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   Optional[Any]:
            return BertTokenizerFast.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self			,  **__lowerCamelCase							)	->   Tuple:
            return FlavaImageProcessor.from_pretrained(self.tmpdirname			,  **__lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   int:
            shutil.rmtree(self.tmpdirname							)




       def 			UpperCamelCase_	(					self							)	->   Optional[int]:
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							[np.random.randint(2_5_5			,  size=(3, 3_0, 4_0_0)			,  dtype=np.uinta							)]

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							[Image.fromarray(np.moveaxis(__lowerCamelCase			,  0			,  -1							)							) for x in image_inputs]

            return image_inputs




       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.get_tokenizer()
            _SCREAMING_SNAKE_CASE				:		Any  			=							self.get_rust_tokenizer()
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.get_image_processor()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)
            processor_slow.save_pretrained(self.tmpdirname							)
            _SCREAMING_SNAKE_CASE				:		Tuple  			=							FlavaProcessor.from_pretrained(self.tmpdirname			,  use_fast=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)
            processor_fast.save_pretrained(self.tmpdirname							)
            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor.from_pretrained(self.tmpdirname							)

            self.assertEqual(processor_slow.tokenizer.get_vocab()			,  tokenizer_slow.get_vocab()							)
            self.assertEqual(processor_fast.tokenizer.get_vocab()			,  tokenizer_fast.get_vocab()							)
            self.assertEqual(tokenizer_slow.get_vocab()			,  tokenizer_fast.get_vocab()							)
            self.assertIsInstance(processor_slow.tokenizer			,  __lowerCamelCase							)
            self.assertIsInstance(processor_fast.tokenizer			,  __lowerCamelCase							)

            self.assertEqual(processor_slow.image_processor.to_json_string()			,  image_processor.to_json_string()							)
            self.assertEqual(processor_fast.image_processor.to_json_string()			,  image_processor.to_json_string()							)
            self.assertIsInstance(processor_slow.image_processor			,  __lowerCamelCase							)
            self.assertIsInstance(processor_fast.image_processor			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   Optional[int]:
            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor(tokenizer=self.get_tokenizer()			,  image_processor=self.get_image_processor()							)
            processor.save_pretrained(self.tmpdirname							)

            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_tokenizer(bos_token="(BOS)"			,  eos_token="(EOS)"							)
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							self.get_image_processor(do_normalize=__lowerCamelCase			,  padding_value=1.0							)

            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor.from_pretrained(
                self.tmpdirname			,  bos_token="(BOS)"			,  eos_token="(EOS)"			,  do_normalize=__lowerCamelCase			,  padding_value=1.0							)

            self.assertEqual(processor.tokenizer.get_vocab()			,  tokenizer_add_kwargs.get_vocab()							)
            self.assertIsInstance(processor.tokenizer			,  __lowerCamelCase							)

            self.assertEqual(processor.image_processor.to_json_string()			,  image_processor_add_kwargs.to_json_string()							)
            self.assertIsInstance(processor.image_processor			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		Any  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		int  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[str]  			=							image_processor(__lowerCamelCase			,  return_tensors="np"							)
            _SCREAMING_SNAKE_CASE				:		str  			=							processor(images=__lowerCamelCase			,  return_tensors="np"							)

            for key in input_feat_extract.keys():
                 self.assertAlmostEqual(input_feat_extract[key].sum()			,  input_processor[key].sum()			,  delta=1E-2							)

            # With rest of the args
            random.seed(1_2_3_4							)
            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							image_processor(
                __lowerCamelCase			,  return_image_mask=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_tensors="np"							)
            random.seed(1_2_3_4							)
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							processor(
                images=__lowerCamelCase			,  return_image_mask=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_tensors="np"							)

            for key in input_feat_extract.keys():
                 self.assertAlmostEqual(input_feat_extract[key].sum()			,  input_processor[key].sum()			,  delta=1E-2							)




       def 			UpperCamelCase_	(					self							)	->   int:
            _SCREAMING_SNAKE_CASE				:		Any  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							"lower newer"

            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							processor(text=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		List[str]  			=							tokenizer(__lowerCamelCase							)

            for key in encoded_tok.keys():
                 self.assertListEqual(encoded_tok[key]			,  encoded_processor[key]							)




       def 			UpperCamelCase_	(					self							)	->   Tuple:
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Any  			=							"lower newer"
            _SCREAMING_SNAKE_CASE				:		Dict  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase							)

            self.assertListEqual(list(inputs.keys()							)			,  ["input_ids", "token_type_ids", "attention_mask", "pixel_values"]							)

            # add extra args
            _SCREAMING_SNAKE_CASE				:		Tuple  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase			,  return_codebook_pixels=__lowerCamelCase			,  return_image_mask=__lowerCamelCase							)

            self.assertListEqual(
                list(inputs.keys()							)			,  [
                    "input_ids",
                    "token_type_ids",
                    "attention_mask",
                    "pixel_values",
                    "codebook_pixel_values",
                    "bool_masked_pos",
                ]			,  )

            # test if it raises when no input is passed
            with pytest.raises(__lowerCamelCase							):
                 processor()




       def 			UpperCamelCase_	(					self							)	->   Dict:
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		str  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		int  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

            _SCREAMING_SNAKE_CASE				:		Dict  			=							processor.batch_decode(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE				:		Any  			=							tokenizer.batch_decode(__lowerCamelCase							)

            self.assertListEqual(__lowerCamelCase			,  __lowerCamelCase							)







       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		int  			=							self.get_image_processor()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							self.get_tokenizer()

            _SCREAMING_SNAKE_CASE				:		Dict  			=							FlavaProcessor(tokenizer=__lowerCamelCase			,  image_processor=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							"lower newer"
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							self.prepare_image_inputs()

            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							processor(text=__lowerCamelCase			,  images=__lowerCamelCase							)

            self.assertListEqual(list(inputs.keys()							)			,  processor.model_input_names							)