



'''simple docstring'''





from random import randint, random




def        lowerCamelCase  (				_snake_case  :						int     ,_snake_case  :						int     ,_snake_case  :						int     ,_snake_case  :						bool = False     ,_snake_case  :						bool = False     ,_snake_case  :						int = 5     ,):





    '''simple docstring'''


    lowercase__		       =						[[-1] * number_of_cells]  # Create a highway without any car
    lowercase__		       =						0
    lowercase__		       =						max(_snake_case     ,0       )
    while i < number_of_cells:
        lowercase__		       =						(
            randint(0     ,_snake_case       ) if random_speed else initial_speed
        )  # Place the cars
        i += (
            randint(1     ,max_speed * 2       ) if random_frequency else frequency
        )  # Arbitrary number, may need tuning
    return highway




def        lowerCamelCase  (				_snake_case  :						list     ,_snake_case  :						int       ):





    '''simple docstring'''


    lowercase__		       =						0
    lowercase__		       =						highway_now[car_index + 1 :]
    for cell in range(len(_snake_case       )       ):  # May need a better name for this
        if cells[cell] != -1:  # If the cell is not empty then
            return distance  # we have the distance we wanted
        distance += 1
    # Here if the car is near the end of the highway
    return distance + get_distance(_snake_case     ,-1       )




def        lowerCamelCase  (				_snake_case  :						list     ,_snake_case  :						float     ,_snake_case  :						int       ):





    '''simple docstring'''


    lowercase__		       =						len(_snake_case       )
    # Beforce calculations, the highway is empty
    lowercase__		       =						[-1] * number_of_cells

    for car_index in range(_snake_case       ):
        if highway_now[car_index] != -1:
            # Add 1 to the current speed of the car and cap the speed
            lowercase__		       =						min(highway_now[car_index] + 1     ,_snake_case       )
            # Number of empty cell before the next car
            lowercase__		       =						get_distance(_snake_case     ,_snake_case       ) - 1
            # We can't have the car causing an accident
            lowercase__		       =						min(next_highway[car_index]     ,_snake_case       )
            if random() < probability:
                # Randomly, a driver will slow down
                lowercase__		       =						max(next_highway[car_index] - 1     ,0       )
    return next_highway




def        lowerCamelCase  (				_snake_case  :						list     ,_snake_case  :						int     ,_snake_case  :						float     ,_snake_case  :						int       ):





    '''simple docstring'''


    lowercase__		       =						len(highway[0]       )

    for i in range(_snake_case       ):
        lowercase__		       =						update(highway[i]     ,_snake_case     ,_snake_case       )
        lowercase__		       =						[-1] * number_of_cells

        for car_index in range(_snake_case       ):
            lowercase__		       =						next_speeds_calculated[car_index]
            if speed != -1:
                # Change the position based on the speed (with % to create the loop)
                lowercase__		       =						(car_index + speed) % number_of_cells
                # Commit the change of position
                lowercase__		       =						speed
        highway.append(_snake_case       )

    return highway


if __name__ == "__main__":
 import doctest

 doctest.testmod()









'''simple docstring'''





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 				snake_case (UpperCamelCase		,      unittest.TestCase   ):
       lowerCAmelCase__  :int						   =					TextToVideoSDPipeline
       lowerCAmelCase__  :Union[str, Any]						   =					TEXT_TO_IMAGE_PARAMS
       lowerCAmelCase__  :List[str]						   =					TEXT_TO_IMAGE_BATCH_PARAMS
       # No `output_type`.
       lowerCAmelCase__  :Optional[Any]						   =					frozenset(
           [
               "num_inference_steps",
               "generator",
               "latents",
               "return_dict",
               "callback",
               "callback_steps",
           ]   )



       def 							_a      (				self      )  ->							Optional[int]:
           torch.manual_seed(0      )
           lowercase__		       =						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     ,)
           lowercase__		       =						DDIMScheduler(
               beta_start=0.0_00_85     ,beta_end=0.0_12     ,beta_schedule="scaled_linear"     ,clip_sample=UpperCAmelCase_     ,set_alpha_to_one=UpperCAmelCase_     ,)
           torch.manual_seed(0      )
           lowercase__		       =						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      )
           lowercase__		       =						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     ,)
           lowercase__		       =						CLIPTextModel(UpperCAmelCase_      )
           lowercase__		       =						CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"      )

           lowercase__		       =						{
               "unet": unet,
               "scheduler": scheduler,
               "vae": vae,
               "text_encoder": text_encoder,
               "tokenizer": tokenizer,
           }
           return components



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

           lowercase__		       =						self.get_dummy_inputs(UpperCAmelCase_      )
           lowercase__		       =						"np"
           lowercase__		       =						sd_pipe(**UpperCAmelCase_      ).frames
           lowercase__		       =						frames[0][-3:, -3:, -1]

           assert frames[0].shape == (64, 64, 3)
           lowercase__		       =						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 							_a      (				self      )  ->							List[Any]:
           self._test_attention_slicing_forward_pass(test_mean_pixel_difference=UpperCAmelCase_     ,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 							_a      (				self      )  ->							Dict:
           self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=UpperCAmelCase_     ,expected_max_diff=1E-2      )



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



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



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







       def 							_a      (				self      )  ->							str:
           return super().test_progress_bar()





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



       def 							_a      (				self      )  ->							Optional[int]:
           lowercase__		       =						load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy"      )

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

           lowercase__		       =						"Spiderman is surfing"
           lowercase__		       =						torch.Generator(device="cpu"      ).manual_seed(0      )

           lowercase__		       =						pipe(UpperCAmelCase_     ,generator=UpperCAmelCase_     ,num_inference_steps=25     ,output_type="pt"      ).frames
           lowercase__		       =						video_frames.cpu().numpy()

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







       def 							_a      (				self      )  ->							Optional[int]:
           lowercase__		       =						load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy"      )

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

           lowercase__		       =						"Spiderman is surfing"
           lowercase__		       =						torch.Generator(device="cpu"      ).manual_seed(0      )

           lowercase__		       =						pipe(UpperCAmelCase_     ,generator=UpperCAmelCase_     ,num_inference_steps=2     ,output_type="pt"      ).frames
           lowercase__		       =						video_frames.cpu().numpy()

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




