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 __snake_case       (		lowerCamelCase_     ,	unittest.TestCase	):
   lowerCAmelCase_														=							VideoToVideoSDPipeline
   lowerCAmelCase_														=							TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"}	) - {"image", "width", "height"}
   lowerCAmelCase_														=							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"}	) - {"image"}
   lowerCAmelCase_														=							PipelineTesterMixin.required_optional_params - {"latents"}
   lowerCAmelCase_														=							False

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




   def 			__a		(					self    :       List[str]   ):



     """simple docstring"""






     torch.manual_seed(0   )
     SCREAMING_SNAKE_CASE__    							=   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 ,			)
     SCREAMING_SNAKE_CASE__    							=   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   )
     SCREAMING_SNAKE_CASE__    							=   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=1_28 ,			)
     torch.manual_seed(0   )
     SCREAMING_SNAKE_CASE__    							=   CLIPTextConfig(
         bos_token_id=0 ,			eos_token_id=2 ,			hidden_size=32 ,			intermediate_size=37 ,			layer_norm_eps=1E-05 ,			num_attention_heads=4 ,			num_hidden_layers=5 ,			pad_token_id=1 ,			vocab_size=10_00 ,			hidden_act="""gelu""" ,			projection_dim=5_12 ,			)
     SCREAMING_SNAKE_CASE__    							=   CLIPTextModel(_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

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




   def 			__a		(					self    :       Any ,			_lowercase    :       Union[str, Any] ,			_lowercase    :       Optional[Any]=0   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   floats_tensor((1, 3, 3, 32, 32) ,			rng=random.Random(_lowercase   )   ).to(_lowercase   )

     if str(_lowercase   ).startswith("""mps"""   ):
       SCREAMING_SNAKE_CASE__    							=   torch.manual_seed(_lowercase   )
     else:
       SCREAMING_SNAKE_CASE__    							=   torch.Generator(device=_lowercase   ).manual_seed(_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   {
         """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 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   """cpu"""  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE__    							=   self.get_dummy_components()
     SCREAMING_SNAKE_CASE__    							=   VideoToVideoSDPipeline(**_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   sd_pipe.to(_lowercase   )
     sd_pipe.set_progress_bar_config(disable=_lowercase   )

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

     assert frames[0].shape == (32, 32, 3)
     SCREAMING_SNAKE_CASE__    							=   np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31]   )

     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 			__a		(					self    :       int   ):



     """simple docstring"""






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




   @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""   )
   def 			__a		(					self    :       Optional[int]   ):



     """simple docstring"""






     pass




   @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""   )
   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     pass




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



     """simple docstring"""






     pass




   def 			__a		(					self    :       Union[str, Any]   ):



     """simple docstring"""






     return super().test_progress_bar()







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




   def 			__a		(					self    :       str   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   VideoToVideoSDPipeline.from_pretrained("""cerspense/zeroscope_v2_XL""" ,			torch_dtype=torch.floataa   )
     pipe.enable_model_cpu_offload()

     # 10 frames
     SCREAMING_SNAKE_CASE__    							=   torch.Generator(device="""cpu"""   ).manual_seed(0   )
     SCREAMING_SNAKE_CASE__    							=   torch.randn((1, 10, 3, 10_24, 5_76) ,			generator=_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   video.to("""cuda"""   )

     SCREAMING_SNAKE_CASE__    							=   """Spiderman is surfing"""

     SCREAMING_SNAKE_CASE__    							=   pipe(_lowercase ,			video=_lowercase ,			generator=_lowercase ,			num_inference_steps=3 ,			output_type="""pt"""   ).frames

     SCREAMING_SNAKE_CASE__    							=   np.array([-1.0_45_89_84, -1.1_27_92_97, -0.9_66_30_86, -0.91_50_39_06, -0.75_09_76_56]   )
     assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array   ).sum() < 1E-2

# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# this script dumps information about the environment

import os
import sys

import transformers


__lowerCamelCase    :				Tuple							     =	'''3'''

print('''Python version:''', sys.version)
print('''transformers version:''', transformers.__version__)

try:
   import torch

   print('''Torch version:''', torch.__version__)
   print('''Cuda available:''', torch.cuda.is_available())
   print('''Cuda version:''', torch.version.cuda)
   print('''CuDNN version:''', torch.backends.cudnn.version())
   print('''Number of GPUs available:''', torch.cuda.device_count())
   print('''NCCL version:''', torch.cuda.nccl.version())
except ImportError:
   print('''Torch version:''', None)

try:
   import deepspeed

   print('''DeepSpeed version:''', deepspeed.__version__)
except ImportError:
   print('''DeepSpeed version:''', None)

try:
   import tensorflow as tf

   print('''TensorFlow version:''', tf.__version__)
   print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU''')))
   print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU''')))
except ImportError:
   print('''TensorFlow version:''', None)
