






'''simple docstring'''






import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    UNetaDConditionModel,
    VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




@skip_mps
class a_    (    UpperCamelCase_		,      unittest.TestCase							):
   _snake_case        =							VideoToVideoSDPipeline
   _snake_case        =							TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"""video"""}							) - {"""image""", """width""", """height"""}
   _snake_case        =							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""video"""}							) - {"""image"""}
   _snake_case        =							PipelineTesterMixin.required_optional_params - {"""latents"""}
   _snake_case        =							False

   # No `output_type`.
   _snake_case        =							frozenset(
       [
           """num_inference_steps""",
           """generator""",
           """latents""",
           """return_dict""",
           """callback""",
           """callback_steps""",
       ]							)







   def     SCREAMING_SNAKE_CASE__					(self)			->      Tuple:
      """simple docstring"""






      torch.manual_seed(0)
      __snake_case				:      int     							= 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					,   )
      __snake_case				:      Optional[Any]     							= DDIMScheduler(
          beta_start=0.00_085					,   beta_end=0.012					,   beta_schedule='scaled_linear'					,   clip_sample=__a					,   set_alpha_to_one=__a					,   )
      torch.manual_seed(0)
      __snake_case				:      Dict     							= 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)
      __snake_case				:      Union[str, Any]     							= 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					,   )
      __snake_case				:      int     							= CLIPTextModel(__a)
      __snake_case				:      List[str]     							= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

      __snake_case				:      Optional[Any]     							= {
          'unet': unet,
          'scheduler': scheduler,
          'vae': vae,
          'text_encoder': text_encoder,
          'tokenizer': tokenizer,
      }
      return components







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a=0)			->      Tuple:
      """simple docstring"""






      __snake_case				:      Optional[int]     							= floats_tensor((1, 3, 3, 3_2, 3_2)					,   rng=random.Random(__a)).to(__a)

      if str(__a).startswith('mps'):
         __snake_case				:      int     							= torch.manual_seed(__a)
      else:
         __snake_case				:      List[Any]     							= torch.Generator(device=__a).manual_seed(__a)
      __snake_case				:      List[Any]     							= {
          'prompt': 'A painting of a squirrel eating a burger',
          'video': video,
          'generator': generator,
          'num_inference_steps': 2,
          'guidance_scale': 6.0,
          'output_type': 'pt',
      }
      return inputs







   def     SCREAMING_SNAKE_CASE__					(self)			->      Any:
      """simple docstring"""






      __snake_case				:      Optional[int]     							= 'cpu'  # ensure determinism for the device-dependent torch.Generator
      __snake_case				:      str     							= self.get_dummy_components()
      __snake_case				:      List[Any]     							= VideoToVideoSDPipeline(**__a)
      __snake_case				:      Tuple     							= sd_pipe.to(__a)
      sd_pipe.set_progress_bar_config(disable=__a)

      __snake_case				:      Dict     							= self.get_dummy_inputs(__a)
      __snake_case				:      Dict     							= 'np'
      __snake_case				:      Tuple     							= sd_pipe(**__a).frames
      __snake_case				:      Any     							= frames[0][-3:, -3:, -1]

      assert frames[0].shape == (3_2, 3_2, 3)
      __snake_case				:      List[str]     							= np.array([1_0_6, 1_1_7, 1_1_3, 1_7_4, 1_3_7, 1_1_2, 1_4_8, 1_5_1, 1_3_1])

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







   @unittest.skipIf(
       torch_device != 'cuda' or not is_xformers_available()					,   reason='XFormers attention is only available with CUDA and `xformers` installed'					,   )
   def     SCREAMING_SNAKE_CASE__					(self)			->      Optional[Any]:
      """simple docstring"""






      self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__a					,   expected_max_diff=5E-3)







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






      pass







   @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.')
   def     SCREAMING_SNAKE_CASE__					(self)			->      List[Any]:
      """simple docstring"""






      pass







   @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.')
   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      pass







   def     SCREAMING_SNAKE_CASE__					(self)			->      List[Any]:
      """simple docstring"""






      return super().test_progress_bar()




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







   def     SCREAMING_SNAKE_CASE__					(self)			->      Union[str, Any]:
      """simple docstring"""






      __snake_case				:      Optional[int]     							= VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL'					,   torch_dtype=torch.floataa)
      pipe.enable_model_cpu_offload()

      # 10 frames
      __snake_case				:      List[Any]     							= torch.Generator(device='cpu').manual_seed(0)
      __snake_case				:      List[str]     							= torch.randn((1, 1_0, 3, 1_0_2_4, 5_7_6)					,   generator=__a)
      __snake_case				:      Dict     							= video.to('cuda')

      __snake_case				:      Optional[int]     							= 'Spiderman is surfing'

      __snake_case				:      List[str]     							= pipe(__a					,   video=__a					,   generator=__a					,   num_inference_steps=3					,   output_type='pt').frames

      __snake_case				:      Tuple     							= np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656])
      assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array).sum() < 1E-2







'''simple docstring'''






import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
      from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
      from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
      from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


__A    	=   DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

__A    	=   '''main'''
# Default branch name
__A    	=   '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
__A    	=   '''aaaaaaa'''
# This commit does not exist, so we should 404.

__A    	=   '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
__A    	=   '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''




@contextlib.contextmanager
def        _SCREAMING_SNAKE_CASE  (				)    -> List[Any]:







   """simple docstring"""
   print('Welcome!'  )
   yield
   print('Bye!'  )




@contextlib.contextmanager
def        _SCREAMING_SNAKE_CASE  (				)    -> Optional[Any]:







   """simple docstring"""
   print('Bonjour!'  )
   yield
   print('Au revoir!'  )




class a_    (    unittest.TestCase							):







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      assert transformers.__spec__ is not None
      assert importlib.util.find_spec('transformers') is not None




class a_    (    unittest.TestCase							):







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      int:
      """simple docstring"""






      with ContextManagers([]):
         print('Transformers are awesome!')
      # The print statement adds a new line at the end of the output
      self.assertEqual(mock_stdout.getvalue()					,   'Transformers are awesome!\n')







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      List[str]:
      """simple docstring"""






      with ContextManagers([context_en()]):
         print('Transformers are awesome!')
      # The output should be wrapped with an English welcome and goodbye
      self.assertEqual(mock_stdout.getvalue()					,   'Welcome!\nTransformers are awesome!\nBye!\n')







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      Tuple:
      """simple docstring"""






      with ContextManagers([context_fr(), context_en()]):
         print('Transformers are awesome!')
      # The output should be wrapped with an English and French welcome and goodbye
      self.assertEqual(mock_stdout.getvalue()					,   'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')







   @require_torch
   def     SCREAMING_SNAKE_CASE__					(self)			->      Union[str, Any]:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   ['labels'])
      self.assertEqual(find_labels(__a)					,   ['labels', 'next_sentence_label'])
      self.assertEqual(find_labels(__a)					,   ['start_positions', 'end_positions'])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   ['labels'])







   @require_tf
   def     SCREAMING_SNAKE_CASE__					(self)			->      List[Any]:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   ['labels'])
      self.assertEqual(find_labels(__a)					,   ['labels', 'next_sentence_label'])
      self.assertEqual(find_labels(__a)					,   ['start_positions', 'end_positions'])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   ['labels'])







   @require_flax
   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   [])
      self.assertEqual(find_labels(__a)					,   [])
      self.assertEqual(find_labels(__a)					,   [])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   [])