



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      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):
     UpperCamelCase__		     =					TextToVideoSDPipeline
     UpperCamelCase__		     =					TEXT_TO_IMAGE_PARAMS
     UpperCamelCase__		     =					TEXT_TO_IMAGE_BATCH_PARAMS
     # No `output_type`.
     UpperCamelCase__		     =					frozenset(
         [
             '''num_inference_steps''',
             '''generator''',
             '''latents''',
             '''return_dict''',
             '''callback''',
             '''callback_steps''',
         ]  )




     def 		snake_case_		(					self):
         torch.manual_seed(0)
         A__					=       UNetaDConditionModel(
             block_out_channels=(3_2, 6_4, 6_4, 6_4)			,    layers_per_block=2			,    sample_size=3_2			,    in_channels=4			,    out_channels=4			,    down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''')			,    up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''')			,    cross_attention_dim=3_2			,    attention_head_dim=4			,    )
         A__					=       DDIMScheduler(
             beta_start=0.0_0_0_8_5			,    beta_end=0.0_1_2			,    beta_schedule='''scaled_linear'''			,    clip_sample=a__			,    set_alpha_to_one=a__			,    )
         torch.manual_seed(0)
         A__					=       AutoencoderKL(
             block_out_channels=[3_2, 6_4]			,    in_channels=3			,    out_channels=3			,    down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']			,    up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']			,    latent_channels=4			,    sample_size=1_2_8			,    )
         torch.manual_seed(0)
         A__					=       CLIPTextConfig(
             bos_token_id=0			,    eos_token_id=2			,    hidden_size=3_2			,    intermediate_size=3_7			,    layer_norm_eps=1e-05			,    num_attention_heads=4			,    num_hidden_layers=5			,    pad_token_id=1			,    vocab_size=1_0_0_0			,    hidden_act='''gelu'''			,    projection_dim=5_1_2			,    )
         A__					=       CLIPTextModel(a__)
         A__					=       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

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




     def 		snake_case_		(					self			,    a__			,    a__=0):
         if str(a__).startswith('''mps'''):
             A__					=       torch.manual_seed(a__)
         else:
             A__					=       torch.Generator(device=a__).manual_seed(a__)
         A__					=       {
             '''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 		snake_case_		(					self):
         A__					=       '''cpu'''  # ensure determinism for the device-dependent torch.Generator
         A__					=       self.get_dummy_components()
         A__					=       TextToVideoSDPipeline(**a__)
         A__					=       sd_pipe.to(a__)
         sd_pipe.set_progress_bar_config(disable=a__)

         A__					=       self.get_dummy_inputs(a__)
         A__					=       '''np'''
         A__					=       sd_pipe(**a__).frames
         A__					=       frames[0][-3:, -3:, -1]

         assert frames[0].shape == (6_4, 6_4, 3)
         A__					=       np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0])

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




     def 		snake_case_		(					self):
         self._test_attention_slicing_forward_pass(test_mean_pixel_difference=a__			,    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 		snake_case_		(					self):
         self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=a__			,    expected_max_diff=1e-2)




     @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''')
     def 		snake_case_		(					self):
         pass




     @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''')
     def 		snake_case_		(					self):
         pass




     @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''')
     def 		snake_case_		(					self):
         pass




     def 		snake_case_		(					self):
         return super().test_progress_bar()







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




     def 		snake_case_		(					self):
         A__					=       load_numpy(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy''')

         A__					=       TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''')
         A__					=       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
         A__					=       pipe.to('''cuda''')

         A__					=       '''Spiderman is surfing'''
         A__					=       torch.Generator(device='''cpu''').manual_seed(0)

         A__					=       pipe(a__			,    generator=a__			,    num_inference_steps=2_5			,    output_type='''pt''').frames
         A__					=       video_frames.cpu().numpy()

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




     def 		snake_case_		(					self):
         A__					=       load_numpy(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy''')

         A__					=       TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''')
         A__					=       pipe.to('''cuda''')

         A__					=       '''Spiderman is surfing'''
         A__					=       torch.Generator(device='''cpu''').manual_seed(0)

         A__					=       pipe(a__			,    generator=a__			,    num_inference_steps=2			,    output_type='''pt''').frames
         A__					=       video_frames.cpu().numpy()

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





from manim import *



class      _UpperCAmelCase      (							A__  ):




     def 		snake_case_		(					self):
         A__					=       Rectangle(height=0.5			,    width=0.5)
         A__					=       Rectangle(height=0.2_5			,    width=0.2_5)
         A__					=       Rectangle(height=0.4_6			,    width=0.4_6).set_stroke(width=0)

         A__					=       [mem.copy() for i in range(6)]
         A__					=       [mem.copy() for i in range(6)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       VGroup(a__			,    a__).arrange(a__			,    buff=0)
         A__					=       Text('''CPU'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         cpu.move_to([-2.5, -0.5, 0])
         self.add(a__)

         A__					=       [mem.copy() for i in range(4)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       Text('''GPU'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         gpu.move_to([-1, -1, 0])
         self.add(a__)

         A__					=       [mem.copy() for i in range(6)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)

         A__					=       Text('''Model'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         model.move_to([3, -1.0, 0])
         self.add(a__)

         A__					=       []
         A__					=       []
         A__					=       []

         for i, rect in enumerate(a__):
             rect.set_stroke(a__)

             A__					=       Rectangle(height=0.4_6 / 4			,    width=0.4_6 / 3).set_stroke(width=0.0).set_fill(a__			,    opacity=0.7)

             if i == 0:
                 cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT)			,    buff=0.0_2			,    direction=a__)
                 cpu_target.set_x(cpu_target.get_x() + 0.1)
             elif i == 3:
                 cpu_target.next_to(model_cpu_arr[0]			,    direction=a__			,    buff=0.0)
             else:
                 cpu_target.next_to(model_cpu_arr[i - 1]			,    direction=a__			,    buff=0.0)
             self.add(a__)
             model_cpu_arr.append(a__)

         self.add(*a__			,    *a__			,    *a__)

         A__					=       [mem.copy() for i in range(6)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)

         A__					=       Text('''Loaded Checkpoint'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         checkpoint.move_to([3, 0.5, 0])

         self.add(a__)

         A__					=       []
         A__					=       []

         for i, rect in enumerate(a__):
             A__					=       fill.copy().set_fill(a__			,    opacity=0.7)
             target.move_to(a__)
             ckpt_arr.append(a__)

             A__					=       target.copy()
             if i < 5:
                 cpu_target.move_to(cpu_left_col_base[i + 1])
             else:
                 cpu_target.move_to(cpu_right_col_base[i - 5])
             ckpt_cpu_arr.append(a__)
         self.add(*a__			,    *a__)

         A__					=       Square(side_length=2.2)
         key.move_to([-5, 2, 0])

         A__					=       MarkupText(
             F"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model"			,    font_size=1_8			,    )

         key_text.move_to([-5, 2.4, 0])

         self.add(a__			,    a__)

         A__					=       MarkupText(
             F"<span fgcolor='{BLUE}'>●</span> Checkpoint"			,    font_size=1_8			,    )

         blue_text.next_to(a__			,    DOWN * 2.4			,    aligned_edge=key_text.get_left())
         self.add(a__)

         A__					=       MarkupText(
             F"Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device."			,    font_size=2_4			,    )
         step_a.move_to([2, 2, 0])

         A__					=       [meta_mem.copy() for i in range(6)]
         A__					=       [meta_mem.copy() for i in range(6)]
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       VGroup(*a__).arrange(a__			,    buff=0)
         A__					=       VGroup(a__			,    a__).arrange(a__			,    buff=0)
         A__					=       Text('''Disk'''			,    font_size=2_4)
         A__					=       Group(a__			,    a__).arrange(a__			,    buff=0.5			,    aligned_edge=a__)
         disk.move_to([-4.0, -1.2_5, 0])
         self.play(Write(a__			,    run_time=3)			,    Write(a__			,    run_time=1)			,    Create(a__			,    run_time=1))

         A__					=       []
         for i, rect in enumerate(a__):
             A__					=       rect.copy()
             target.generate_target()
             target.target.move_to(disk_left_col_base[i]).scale(0.5)
             animations.append(MoveToTarget(a__			,    run_time=1.5))
         self.play(*a__)

         self.play(FadeOut(a__))

         A__					=       MarkupText(F"Then, the checkpoint is removed from memory\nthrough garbage collection."			,    font_size=2_4)
         step_a.move_to([2, 2, 0])

         self.play(Write(a__			,    run_time=3))

         self.play(
             FadeOut(a__			,    a__			,    *a__			,    *a__)			,    )

         self.wait()
