


import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer





class   __a			(    lowerCAmelCase_      ):
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				int:




        '''simple docstring'''
        lowercase__:   List[str]  			=   tempfile.mkdtemp()
        lowercase__:   Optional[Any]  			=   5

        # Realm tok
        lowercase__:   Dict  			=   [
            '[UNK]',
            '[CLS]',
            '[SEP]',
            '[PAD]',
            '[MASK]',
            'test',
            'question',
            'this',
            'is',
            'the',
            'first',
            'second',
            'third',
            'fourth',
            'fifth',
            'record',
            'want',
            '##want',
            '##ed',
            'wa',
            'un',
            'runn',
            '##ing',
            ',',
            'low',
            'lowest',
        ]
        lowercase__:   Union[str, Any]  			=   os.path.join(self.tmpdirname				, 'realm_tokenizer' )
        os.makedirs(__snake_case				, exist_ok=__snake_case )
        lowercase__:   Optional[int]  			=   os.path.join(__snake_case				, VOCAB_FILES_NAMES['vocab_file'] )
        with open(self.vocab_file				, 'w'				, encoding='utf-8' ) as vocab_writer:
               vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )

        lowercase__:   Dict  			=   os.path.join(self.tmpdirname				, 'realm_block_records' )
        os.makedirs(__snake_case				, exist_ok=__snake_case )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				RealmTokenizer:




        '''simple docstring'''
        return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname				, 'realm_tokenizer' ) )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				int:




        '''simple docstring'''
        shutil.rmtree(self.tmpdirname )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				int:




        '''simple docstring'''
        lowercase__:   Any  			=   RealmConfig(num_block_records=self.num_block_records )
        return config
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Tuple:




        '''simple docstring'''
        lowercase__:   List[str]  			=   Dataset.from_dict(
            {
                'id': ['0', '1'],
                'question': ['foo', 'bar'],
                'answers': [['Foo', 'Bar'], ['Bar']],
            } )
        return dataset
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[Any]:




        '''simple docstring'''
        lowercase__:   Union[str, Any]  			=   np.array(
            [
                b'This is the first record',
                b'This is the second record',
                b'This is the third record',
                b'This is the fourth record',
                b'This is the fifth record',
                b'This is a longer longer longer record',
            ]				, dtype=__snake_case				, )
        return block_records
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Any:




        '''simple docstring'''
        lowercase__:   Dict  			=   RealmRetriever(
            block_records=self.get_dummy_block_records()				, tokenizer=self.get_tokenizer()				, )
        return retriever
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Union[str, Any]:




        '''simple docstring'''
        lowercase__:   str  			=   self.get_config()
        lowercase__:   Any  			=   self.get_dummy_retriever()
        lowercase__:   Any  			=   retriever.tokenizer

        lowercase__:   Union[str, Any]  			=   np.array([0, 3]				, dtype='long' )
        lowercase__:   List[Any]  			=   tokenizer(['Test question'] ).input_ids
        lowercase__:   Union[str, Any]  			=   tokenizer(
            ['the fourth']				, add_special_tokens=__snake_case				, return_token_type_ids=__snake_case				, return_attention_mask=__snake_case				, ).input_ids
        lowercase__:   Optional[Any]  			=   config.reader_seq_len

        lowercase__			,						lowercase__			,						lowercase__			,						lowercase__:   Tuple  			=   retriever(
            __snake_case				, __snake_case				, answer_ids=__snake_case				, max_length=__snake_case				, return_tensors='np' )

        self.assertEqual(len(__snake_case )				, 2 )
        self.assertEqual(len(__snake_case )				, 2 )
        self.assertEqual(len(__snake_case )				, 2 )
        self.assertEqual(concat_inputs.input_ids.shape				, (2, 10) )
        self.assertEqual(concat_inputs.attention_mask.shape				, (2, 10) )
        self.assertEqual(concat_inputs.token_type_ids.shape				, (2, 10) )
        self.assertEqual(concat_inputs.special_tokens_mask.shape				, (2, 10) )
        self.assertEqual(
            tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] )				, ['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]']				, )
        self.assertEqual(
            tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] )				, ['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]']				, )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[str]:




        '''simple docstring'''
        lowercase__:   str  			=   self.get_config()
        lowercase__:   int  			=   self.get_dummy_retriever()
        lowercase__:   Optional[Any]  			=   retriever.tokenizer

        lowercase__:   Any  			=   np.array([0, 3, 5]				, dtype='long' )
        lowercase__:   Any  			=   tokenizer(['Test question'] ).input_ids
        lowercase__:   int  			=   tokenizer(
            ['the fourth', 'longer longer']				, add_special_tokens=__snake_case				, return_token_type_ids=__snake_case				, return_attention_mask=__snake_case				, ).input_ids
        lowercase__:   int  			=   config.reader_seq_len

        lowercase__			,						lowercase__			,						lowercase__			,						lowercase__:   Dict  			=   retriever(
            __snake_case				, __snake_case				, answer_ids=__snake_case				, max_length=__snake_case				, return_tensors='np' )

        self.assertEqual([False, True, True]				, __snake_case )
        self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]				, __snake_case )
        self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]				, __snake_case )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Union[str, Any]:




        '''simple docstring'''
        lowercase__:   Dict  			=   self.get_dummy_retriever()
        retriever.save_pretrained(os.path.join(self.tmpdirname				, 'realm_block_records' ) )

        # Test local path
        lowercase__:   Optional[int]  			=   retriever.from_pretrained(os.path.join(self.tmpdirname				, 'realm_block_records' ) )
        self.assertEqual(retriever.block_records[0]				, b'This is the first record' )

        # Test mocked remote path
        with patch('transformers.models.realm.retrieval_realm.hf_hub_download' ) as mock_hf_hub_download:
               lowercase__:   Any  			=   os.path.join(
                   os.path.join(self.tmpdirname				, 'realm_block_records' )				, _REALM_BLOCK_RECORDS_FILENAME )
               lowercase__:   str  			=   RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa' )

        self.assertEqual(retriever.block_records[0]				, b'This is the first record' )





import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device


_lowerCAmelCase					:			Optional[Any]  				=			False






class 	__magic_name__    (			unittest.TestCase      ):
			pass






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





			def 		__magic_name__    (		self					)   -> Optional[int]:




						'''simple docstring'''
						__a        =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion'					)
						pipe.to(__snake_case					)
						pipe.set_progress_bar_config(disable=__snake_case					)

						__a        =load_image(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'					)
						__a        =torch.manual_seed(0					)
						__a        =pipe(
						    image=__snake_case					,  generator=__snake_case					,  guidance_scale=7.5					,  num_inference_steps=50					,  output_type='numpy'					,  ).images

						__a        =image[0, 253:256, 253:256, -1]

						assert image.shape == (1, 512, 512, 3)
						__a        =np.array([0.0441, 0.0469, 0.0507, 0.0575, 0.0632, 0.0650, 0.0865, 0.0909, 0.0945]					)

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






