



'''simple docstring'''

import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip 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 OwlViTImageProcessor, OwlViTProcessor

@require_vision
class       __magic_name__		(       unittest.TestCase  ):







							def 				__lowercase     (				self   :			Union[str, Any]						):
									_a	: Dict								=				tempfile.mkdtemp()

									# fmt: off
									_a	: Dict								=				['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
									# fmt: on
									_a	: List[Any]								=				dict(zip(_UpperCAmelCase      ,range(len(_UpperCAmelCase						)						)						)						)
									_a	: Any								=				['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
									_a	: Any								=				{'unk_token': '<unk>'}

									_a	: Any								=				os.path.join(self.tmpdirname      ,VOCAB_FILES_NAMES['vocab_file']						)
									_a	: int								=				os.path.join(self.tmpdirname      ,VOCAB_FILES_NAMES['merges_file']						)
									with open(self.vocab_file      ,'w'      ,encoding='utf-8'						) as fp:
											fp.write(json.dumps(_UpperCAmelCase						) + '\n'						)
									with open(self.merges_file      ,'w'      ,encoding='utf-8'						) as fp:
											fp.write('\n'.join(_UpperCAmelCase						)						)

									_a	: Any								=				{
									    'do_resize': True,
									    'size': 20,
									    'do_center_crop': True,
									    'crop_size': 18,
									    'do_normalize': True,
									    'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73],
									    'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11],
									}
									_a	: Tuple								=				os.path.join(self.tmpdirname      ,_UpperCAmelCase						)
									with open(self.image_processor_file      ,'w'      ,encoding='utf-8'						) as fp:
											json.dump(_UpperCAmelCase      ,_UpperCAmelCase						)







							def 				__lowercase     (				self   :			int      ,**_UpperCAmelCase   :			Any						):
									return CLIPTokenizer.from_pretrained(self.tmpdirname      ,pad_token='!'      ,**_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Dict      ,**_UpperCAmelCase   :			Dict						):
									return CLIPTokenizerFast.from_pretrained(self.tmpdirname      ,pad_token='!'      ,**_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Optional[int]      ,**_UpperCAmelCase   :			Union[str, Any]						):
									return OwlViTImageProcessor.from_pretrained(self.tmpdirname      ,**_UpperCAmelCase						)







							def 				__lowercase     (				self   :			int						):
									shutil.rmtree(self.tmpdirname						)







							def 				__lowercase     (				self   :			List[str]						):
									_a	: int								=				[np.random.randint(255      ,size=(3, 30, 400)      ,dtype=np.uinta						)]

									_a	: Optional[int]								=				[Image.fromarray(np.moveaxis(_UpperCAmelCase      ,0      ,-1						)						) for x in image_inputs]

									return image_inputs







							def 				__lowercase     (				self   :			Any						):
									_a	: List[str]								=				self.get_tokenizer()
									_a	: List[Any]								=				self.get_rust_tokenizer()
									_a	: Optional[Any]								=				self.get_image_processor()

									_a	: Tuple								=				OwlViTProcessor(tokenizer=_UpperCAmelCase      ,image_processor=_UpperCAmelCase						)
									processor_slow.save_pretrained(self.tmpdirname						)
									_a	: List[str]								=				OwlViTProcessor.from_pretrained(self.tmpdirname      ,use_fast=_UpperCAmelCase						)

									_a	: Optional[Any]								=				OwlViTProcessor(tokenizer=_UpperCAmelCase      ,image_processor=_UpperCAmelCase						)
									processor_fast.save_pretrained(self.tmpdirname						)
									_a	: List[Any]								=				OwlViTProcessor.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      ,_UpperCAmelCase						)
									self.assertIsInstance(processor_fast.tokenizer      ,_UpperCAmelCase						)

									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      ,_UpperCAmelCase						)
									self.assertIsInstance(processor_fast.image_processor      ,_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Any						):
									_a	: Tuple								=				OwlViTProcessor(tokenizer=self.get_tokenizer()      ,image_processor=self.get_image_processor()						)
									processor.save_pretrained(self.tmpdirname						)

									_a	: Optional[Any]								=				self.get_tokenizer(bos_token='(BOS)'      ,eos_token='(EOS)'						)
									_a	: Dict								=				self.get_image_processor(do_normalize=_UpperCAmelCase						)

									_a	: Dict								=				OwlViTProcessor.from_pretrained(
									    self.tmpdirname      ,bos_token='(BOS)'      ,eos_token='(EOS)'      ,do_normalize=_UpperCAmelCase						)

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

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







							def 				__lowercase     (				self   :			Dict						):
									_a	: str								=				self.get_image_processor()
									_a	: List[Any]								=				self.get_tokenizer()

									_a	: List[Any]								=				OwlViTProcessor(tokenizer=_UpperCAmelCase      ,image_processor=_UpperCAmelCase						)

									_a	: str								=				self.prepare_image_inputs()

									_a	: Any								=				image_processor(_UpperCAmelCase      ,return_tensors='np'						)
									_a	: Optional[Any]								=				processor(images=_UpperCAmelCase      ,return_tensors='np'						)

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







							def 				__lowercase     (				self   :			List[str]						):
									_a	: List[Any]								=				self.get_image_processor()
									_a	: Optional[int]								=				self.get_tokenizer()

									_a	: Optional[Any]								=				OwlViTProcessor(tokenizer=_UpperCAmelCase      ,image_processor=_UpperCAmelCase						)

									_a	: Optional[int]								=				'lower newer'

									_a	: List[str]								=				processor(text=_UpperCAmelCase      ,return_tensors='np'						)

									_a	: Union[str, Any]								=				tokenizer(_UpperCAmelCase      ,return_tensors='np'						)

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







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: Optional[Any]								=				self.get_image_processor()
									_a	: Optional[Any]								=				self.get_tokenizer()

									_a	: List[str]								=				OwlViTProcessor(tokenizer=_UpperCAmelCase      ,image_processor=_UpperCAmelCase						)

									_a	: int								=				'lower newer'
									_a	: Union[str, Any]								=				self.prepare_image_inputs()

									_a	: List[str]								=				processor(text=_UpperCAmelCase      ,images=_UpperCAmelCase						)

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

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







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: Union[str, Any]								=				'google/owlvit-base-patch32'
									_a	: Any								=				OwlViTProcessor.from_pretrained(_UpperCAmelCase						)

									_a	: Optional[int]								=				['cat', 'nasa badge']
									_a	: Optional[int]								=				processor(text=_UpperCAmelCase						)

									_a	: Union[str, Any]								=				16
									self.assertListEqual(list(inputs.keys()						)      ,['input_ids', 'attention_mask']						)
									self.assertEqual(inputs['input_ids'].shape      ,(2, seq_length)						)

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







							def 				__lowercase     (				self   :			Union[str, Any]						):
									_a	: Dict								=				'google/owlvit-base-patch32'
									_a	: Dict								=				OwlViTProcessor.from_pretrained(_UpperCAmelCase						)

									_a	: Optional[int]								=				[['cat', 'nasa badge'], ['person']]
									_a	: List[Any]								=				processor(text=_UpperCAmelCase						)

									_a	: List[str]								=				16
									_a	: Tuple								=				len(_UpperCAmelCase						)
									_a	: Union[str, Any]								=				max([len(_UpperCAmelCase						) for texts in input_texts]						)

									self.assertListEqual(list(inputs.keys()						)      ,['input_ids', 'attention_mask']						)
									self.assertEqual(inputs['input_ids'].shape      ,(batch_size * num_max_text_queries, seq_length)						)

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







							def 				__lowercase     (				self   :			Dict						):
									_a	: Any								=				'google/owlvit-base-patch32'
									_a	: List[Any]								=				OwlViTProcessor.from_pretrained(_UpperCAmelCase						)

									_a	: int								=				['cat', 'nasa badge']
									_a	: str								=				processor(text=_UpperCAmelCase						)

									_a	: Union[str, Any]								=				16
									_a	: Any								=				inputs['input_ids']
									_a	: List[Any]								=				[
									    [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
									    [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
									]

									self.assertListEqual(list(inputs.keys()						)      ,['input_ids', 'attention_mask']						)
									self.assertEqual(inputs['input_ids'].shape      ,(2, seq_length)						)
									self.assertListEqual(list(input_ids[0]						)      ,predicted_ids[0]						)
									self.assertListEqual(list(input_ids[1]						)      ,predicted_ids[1]						)







							def 				__lowercase     (				self   :			Dict						):
									_a	: List[Any]								=				self.get_image_processor()
									_a	: Optional[int]								=				self.get_tokenizer()

									_a	: Union[str, Any]								=				OwlViTProcessor(tokenizer=_UpperCAmelCase      ,image_processor=_UpperCAmelCase						)

									_a	: Any								=				self.prepare_image_inputs()
									_a	: Optional[int]								=				self.prepare_image_inputs()

									_a	: Union[str, Any]								=				processor(images=_UpperCAmelCase      ,query_images=_UpperCAmelCase						)

									self.assertListEqual(list(inputs.keys()						)      ,['query_pixel_values', 'pixel_values']						)

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







							def 				__lowercase     (				self   :			Union[str, Any]						):
									_a	: Dict								=				self.get_image_processor()
									_a	: Optional[Any]								=				self.get_tokenizer()

									_a	: Optional[Any]								=				OwlViTProcessor(tokenizer=_UpperCAmelCase      ,image_processor=_UpperCAmelCase						)

									_a	: Dict								=				[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

									_a	: Optional[Any]								=				processor.batch_decode(_UpperCAmelCase						)
									_a	: List[str]								=				tokenizer.batch_decode(_UpperCAmelCase						)

									self.assertListEqual(_UpperCAmelCase      ,_UpperCAmelCase						)









'''simple docstring'''

import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()

class       __magic_name__		(       unittest.TestCase  ):







							@property
							def 				__lowercase     (				self   :			int						):
									torch.manual_seed(0						)
									_a	: int								=				UNetaDModel(
									    block_out_channels=(32, 64)      ,layers_per_block=2      ,sample_size=32      ,in_channels=3      ,out_channels=3      ,down_block_types=('DownBlock2D', 'AttnDownBlock2D')      ,up_block_types=('AttnUpBlock2D', 'UpBlock2D')      ,)
									return model







							@property
							def 				__lowercase     (				self   :			Any						):
									torch.manual_seed(0						)
									_a	: int								=				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







							@property
							def 				__lowercase     (				self   :			Union[str, Any]						):
									torch.manual_seed(0						)
									_a	: Dict								=				CLIPTextConfig(
									    bos_token_id=0      ,eos_token_id=2      ,hidden_size=32      ,intermediate_size=37      ,layer_norm_eps=1E-05      ,num_attention_heads=4      ,num_hidden_layers=5      ,pad_token_id=1      ,vocab_size=1000      ,)
									return CLIPTextModel(_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Dict						):
									_a	: Union[str, Any]								=				self.dummy_uncond_unet
									_a	: Union[str, Any]								=				DDIMScheduler()
									_a	: Union[str, Any]								=				self.dummy_vq_model

									_a	: List[Any]								=				LDMPipeline(unet=_UpperCAmelCase      ,vqvae=_UpperCAmelCase      ,scheduler=_UpperCAmelCase						)
									ldm.to(_UpperCAmelCase						)
									ldm.set_progress_bar_config(disable=_UpperCAmelCase						)

									_a	: Dict								=				torch.manual_seed(0						)
									_a	: int								=				ldm(generator=_UpperCAmelCase      ,num_inference_steps=2      ,output_type='numpy'						).images

									_a	: Tuple								=				torch.manual_seed(0						)
									_a	: List[Any]								=				ldm(generator=_UpperCAmelCase      ,num_inference_steps=2      ,output_type='numpy'      ,return_dict=_UpperCAmelCase						)[0]

									_a	: Any								=				image[0, -3:, -3:, -1]
									_a	: List[Any]								=				image_from_tuple[0, -3:, -3:, -1]

									assert image.shape == (1, 64, 64, 3)
									_a	: Union[str, Any]								=				np.array([0.85_12, 0.8_18, 0.64_11, 0.68_08, 0.44_65, 0.56_18, 0.46, 0.62_31, 0.51_72]						)
									_a	: Any								=				1E-2 if torch_device != 'mps' else 3E-2

									assert np.abs(image_slice.flatten() - expected_slice						).max() < tolerance
									assert np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < tolerance

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







							def 				__lowercase     (				self   :			Optional[int]						):
									_a	: Dict								=				LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256'						)
									ldm.to(_UpperCAmelCase						)
									ldm.set_progress_bar_config(disable=_UpperCAmelCase						)

									_a	: str								=				torch.manual_seed(0						)
									_a	: Optional[Any]								=				ldm(generator=_UpperCAmelCase      ,num_inference_steps=5      ,output_type='numpy'						).images

									_a	: Optional[Any]								=				image[0, -3:, -3:, -1]

									assert image.shape == (1, 256, 256, 3)
									_a	: Union[str, Any]								=				np.array([0.43_99, 0.4_49_75, 0.4_68_25, 0.4_74, 0.43_59, 0.45_81, 0.4_50_95, 0.43_41, 0.44_47]						)
									_a	: List[str]								=				1E-2 if torch_device != 'mps' else 3E-2

									assert np.abs(image_slice.flatten() - expected_slice						).max() < tolerance




