import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    TextToVideoSDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


@skip_mps
class 			lowerCamelCase_  (     UpperCAmelCase_		,			unittest.TestCase				):






    '''simple docstring'''






    a__			:		Optional[Any]      			=   TextToVideoSDPipeline
    a__			:		Union[str, Any]      			=   TEXT_TO_IMAGE_PARAMS
    a__			:		Dict      			=   TEXT_TO_IMAGE_BATCH_PARAMS
    # No `output_type`.
    a__			:		Optional[int]      			=   frozenset(
        [
            """num_inference_steps""",
            """generator""",
            """latents""",
            """return_dict""",
            """callback""",
            """callback_steps""",
        ]				)







    def     UpperCamelCase__     (			self) ->			Any:
        torch.manual_seed(0)
        __UpperCamelCase  :Optional[Any]    						=	UNetaDConditionModel(
            block_out_channels=(32, 64, 64, 64)				,				layers_per_block=2				,				sample_size=32				,				in_channels=4				,				out_channels=4				,				down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''')				,				up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''')				,				cross_attention_dim=32				,				attention_head_dim=4				,				)
        __UpperCamelCase  :int    						=	DDIMScheduler(
            beta_start=0.0_00_85				,				beta_end=0.0_12				,				beta_schedule='''scaled_linear'''				,				clip_sample=__lowercase				,				set_alpha_to_one=__lowercase				,				)
        torch.manual_seed(0)
        __UpperCamelCase  :int    						=	AutoencoderKL(
            block_out_channels=[32, 64]				,				in_channels=3				,				out_channels=3				,				down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']				,				up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']				,				latent_channels=4				,				sample_size=128				,				)
        torch.manual_seed(0)
        __UpperCamelCase  :Tuple    						=	CLIPTextConfig(
            bos_token_id=0				,				eos_token_id=2				,				hidden_size=32				,				intermediate_size=37				,				layer_norm_eps=1E-0_5				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=1_000				,				hidden_act='''gelu'''				,				projection_dim=512				,				)
        __UpperCamelCase  :Optional[int]    						=	CLIPTextModel(__lowercase)
        __UpperCamelCase  :Optional[int]    						=	CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

        __UpperCamelCase  :str    						=	{
            '''unet''': unet,
            '''scheduler''': scheduler,
            '''vae''': vae,
            '''text_encoder''': text_encoder,
            '''tokenizer''': tokenizer,
        }
        return components







    def     UpperCamelCase__     (			self				,				__lowercase				,				__lowercase=0) ->			Optional[int]:
        if str(__lowercase).startswith('''mps'''):
            __UpperCamelCase  :Optional[int]    						=	torch.manual_seed(__lowercase)
        else:
            __UpperCamelCase  :Dict    						=	torch.Generator(device=__lowercase).manual_seed(__lowercase)
        __UpperCamelCase  :Optional[int]    						=	{
            '''prompt''': '''A painting of a squirrel eating a burger''',
            '''generator''': generator,
            '''num_inference_steps''': 2,
            '''guidance_scale''': 6.0,
            '''output_type''': '''pt''',
        }
        return inputs







    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        __UpperCamelCase  :Dict    						=	'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        __UpperCamelCase  :Optional[int]    						=	self.get_dummy_components()
        __UpperCamelCase  :Dict    						=	TextToVideoSDPipeline(**__lowercase)
        __UpperCamelCase  :List[Any]    						=	sd_pipe.to(__lowercase)
        sd_pipe.set_progress_bar_config(disable=__lowercase)

        __UpperCamelCase  :Any    						=	self.get_dummy_inputs(__lowercase)
        __UpperCamelCase  :Any    						=	'''np'''
        __UpperCamelCase  :List[str]    						=	sd_pipe(**__lowercase).frames
        __UpperCamelCase  :Union[str, Any]    						=	frames[0][-3:, -3:, -1]

        assert frames[0].shape == (64, 64, 3)
        __UpperCamelCase  :Any    						=	np.array([1_58.0, 1_60.0, 1_53.0, 1_25.0, 1_00.0, 1_21.0, 1_11.0, 93.0, 1_13.0])

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







    def     UpperCamelCase__     (			self) ->			List[str]:
        self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__lowercase				,				expected_max_diff=3E-3)







    @unittest.skipIf(
        torch_device != '''cuda''' or not is_xformers_available()				,				reason='''XFormers attention is only available with CUDA and `xformers` installed'''				,				)
    def     UpperCamelCase__     (			self) ->			Dict:
        self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__lowercase				,				expected_max_diff=1E-2)







    @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''')
    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        pass







    @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''')
    def     UpperCamelCase__     (			self) ->			Optional[int]:
        pass







    @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''')
    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        pass







    def     UpperCamelCase__     (			self) ->			Any:
        return super().test_progress_bar()


@slow
@skip_mps
class 			lowerCamelCase_  (     unittest.TestCase				):






    '''simple docstring'''






    def     UpperCamelCase__     (			self) ->			str:
        __UpperCamelCase  :int    						=	load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy''')

        __UpperCamelCase  :Any    						=	TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''')
        __UpperCamelCase  :int    						=	DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
        __UpperCamelCase  :Optional[Any]    						=	pipe.to('''cuda''')

        __UpperCamelCase  :List[Any]    						=	'''Spiderman is surfing'''
        __UpperCamelCase  :List[str]    						=	torch.Generator(device='''cpu''').manual_seed(0)

        __UpperCamelCase  :Dict    						=	pipe(__lowercase				,				generator=__lowercase				,				num_inference_steps=25				,				output_type='''pt''').frames
        __UpperCamelCase  :str    						=	video_frames.cpu().numpy()

        assert np.abs(expected_video - video).mean() < 5E-2







    def     UpperCamelCase__     (			self) ->			Dict:
        __UpperCamelCase  :Tuple    						=	load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy''')

        __UpperCamelCase  :List[str]    						=	TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''')
        __UpperCamelCase  :Union[str, Any]    						=	pipe.to('''cuda''')

        __UpperCamelCase  :Optional[int]    						=	'''Spiderman is surfing'''
        __UpperCamelCase  :List[Any]    						=	torch.Generator(device='''cpu''').manual_seed(0)

        __UpperCamelCase  :Tuple    						=	pipe(__lowercase				,				generator=__lowercase				,				num_inference_steps=2				,				output_type='''pt''').frames
        __UpperCamelCase  :int    						=	video_frames.cpu().numpy()

        assert np.abs(expected_video - video).mean() < 5E-2






import os
import unittest

from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer
from transformers.testing_utils import require_jieba, tooslow

from ...test_tokenization_common import TokenizerTesterMixin


@require_jieba
class 			lowerCamelCase_  (     UpperCAmelCase_		,			unittest.TestCase				):






    '''simple docstring'''






    a__			:		Any      			=   CpmAntTokenizer
    a__			:		Optional[Any]      			=   False







    def     UpperCamelCase__     (			self) ->			Any:
        super().setUp()

        __UpperCamelCase  :Optional[int]    						=	[
            '''<d>''',
            '''</d>''',
            '''<s>''',
            '''</s>''',
            '''</_>''',
            '''<unk>''',
            '''<pad>''',
            '''</n>''',
            '''我''',
            '''是''',
            '''C''',
            '''P''',
            '''M''',
            '''A''',
            '''n''',
            '''t''',
        ]
        __UpperCamelCase  :Optional[int]    						=	os.path.join(self.tmpdirname				,				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]))







    @tooslow
    def     UpperCamelCase__     (			self) ->			Dict:
        __UpperCamelCase  :Tuple    						=	CpmAntTokenizer.from_pretrained('''openbmb/cpm-ant-10b''')
        __UpperCamelCase  :Dict    						=	'''今天天气真好！'''
        __UpperCamelCase  :Tuple    						=	['''今天''', '''天气''', '''真''', '''好''', '''！''']
        __UpperCamelCase  :Optional[Any]    						=	tokenizer.tokenize(__lowercase)
        self.assertListEqual(__lowercase				,				__lowercase)
        __UpperCamelCase  :int    						=	'''今天天气真好！'''
        __UpperCamelCase  :List[str]    						=	[tokenizer.bos_token] + tokens

        __UpperCamelCase  :List[str]    						=	[6, 9_802, 14_962, 2_082, 831, 244]
        self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowercase)				,				__lowercase)

        __UpperCamelCase  :Dict    						=	tokenizer.decode(__lowercase)
        self.assertEqual(__lowercase				,				__lowercase)





