





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



      def 	lowerCAmelCase__    (	self:						Optional[int]       )						->    Optional[Any]:
         '''simple docstring'''

         torch.manual_seed(0       )
         UpperCAmelCase_											=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_											=DDIMScheduler(
             beta_start=0.0_00_85		,  beta_end=0.0_12		,  beta_schedule="scaled_linear"		,  clip_sample=_lowerCAmelCase		,  set_alpha_to_one=_lowerCAmelCase		,  )
         torch.manual_seed(0       )
         UpperCAmelCase_											=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_											=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=1000		,  hidden_act="gelu"		,  projection_dim=512		,  )
         UpperCAmelCase_											=CLIPTextModel(_lowerCAmelCase       )
         UpperCAmelCase_											=CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

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



      def 	lowerCAmelCase__    (	self:						Optional[int]		,  _lowerCAmelCase:						Union[str, Any]		,  _lowerCAmelCase:						List[str]=0       )						->    Optional[int]:
         '''simple docstring'''

         if str(_lowerCAmelCase       ).startswith("mps"       ):
            UpperCAmelCase_											=torch.manual_seed(_lowerCAmelCase       )
         else:
            UpperCAmelCase_											=torch.Generator(device=_lowerCAmelCase       ).manual_seed(_lowerCAmelCase       )
         UpperCAmelCase_											={
             "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 	lowerCAmelCase__    (	self:						Any       )						->    Tuple:
         '''simple docstring'''

         UpperCAmelCase_											="cpu"  # ensure determinism for the device-dependent torch.Generator
         UpperCAmelCase_											=self.get_dummy_components()
         UpperCAmelCase_											=TextToVideoSDPipeline(**_lowerCAmelCase       )
         UpperCAmelCase_											=sd_pipe.to(_lowerCAmelCase       )
         sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

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

         assert frames[0].shape == (64, 64, 3)
         UpperCAmelCase_											=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 	lowerCAmelCase__    (	self:						Tuple       )						->    Any:
         '''simple docstring'''

         self._test_attention_slicing_forward_pass(test_mean_pixel_difference=_lowerCAmelCase		,  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 	lowerCAmelCase__    (	self:						str       )						->    Optional[int]:
         '''simple docstring'''

         self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_lowerCAmelCase		,  expected_max_diff=1e-2       )



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

         pass



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

         pass



      @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline."       )
      def 	lowerCAmelCase__    (	self:						Any       )						->    Optional[Any]:
         '''simple docstring'''

         pass






      def 	lowerCAmelCase__    (	self:						Optional[Any]       )						->    Tuple:
         '''simple docstring'''

         return super().test_progress_bar()

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



      def 	lowerCAmelCase__    (	self:						Tuple       )						->    Union[str, Any]:
         '''simple docstring'''

         UpperCAmelCase_											=load_numpy(
             "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy"       )

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

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

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

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






      def 	lowerCAmelCase__    (	self:						str       )						->    List[Any]:
         '''simple docstring'''

         UpperCAmelCase_											=load_numpy(
             "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy"       )

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

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

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

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











import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


__lowercase  :   Any						      ="""hf-internal-testing/tiny-random-bert"""
__lowercase  :   List[str]						      =os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
__lowercase  :   Dict						      ="""9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""

class      A       (	unittest.TestCase						):



      def 	lowerCAmelCase__    (	self:						List[str]       )						->    str:
         '''simple docstring'''

         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  _lowerCAmelCase       )
         # Should have downloaded the file in here
         self.assertTrue(os.path.isdir(_lowerCAmelCase       )       )
         # Cache should contain at least those three subfolders:
         for subfolder in ["blobs", "refs", "snapshots"]:
            self.assertTrue(os.path.isdir(os.path.join(_lowerCAmelCase		,  _lowerCAmelCase       )       )       )
         with open(os.path.join(_lowerCAmelCase		,  "refs"		,  "main"       )       ) as f:
            UpperCAmelCase_											=f.read()
         self.assertEqual(_lowerCAmelCase		,  os.path.join(_lowerCAmelCase		,  "snapshots"		,  _lowerCAmelCase		,  _lowerCAmelCase       )       )
         self.assertTrue(os.path.isfile(_lowerCAmelCase       )       )

         # File is cached at the same place the second time.
         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  _lowerCAmelCase       )
         self.assertEqual(_lowerCAmelCase		,  _lowerCAmelCase       )

         # Using a specific revision to test the full commit hash.
         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  _lowerCAmelCase		,  revision="9b8c223"       )
         self.assertEqual(_lowerCAmelCase		,  os.path.join(_lowerCAmelCase		,  "snapshots"		,  _lowerCAmelCase		,  _lowerCAmelCase       )       )



      def 	lowerCAmelCase__    (	self:						Any       )						->    Optional[Any]:
         '''simple docstring'''

         with self.assertRaisesRegex(_lowerCAmelCase		,  "is not a valid model identifier"       ):
            UpperCAmelCase_											=cached_file("tiny-random-bert"		,  _lowerCAmelCase       )

         with self.assertRaisesRegex(_lowerCAmelCase		,  "is not a valid git identifier"       ):
            UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  _lowerCAmelCase		,  revision="aaaa"       )

         with self.assertRaisesRegex(_lowerCAmelCase		,  "does not appear to have a file named"       ):
            UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"       )



      def 	lowerCAmelCase__    (	self:						Tuple       )						->    Optional[Any]:
         '''simple docstring'''

         with self.assertRaisesRegex(_lowerCAmelCase		,  "does not appear to have a file named"       ):
            UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"       )

         with open(os.path.join(_lowerCAmelCase		,  "refs"		,  "main"       )       ) as f:
            UpperCAmelCase_											=f.read()
         self.assertTrue(os.path.isfile(os.path.join(_lowerCAmelCase		,  ".no_exist"		,  _lowerCAmelCase		,  "conf"       )       )       )

         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"		,  _raise_exceptions_for_missing_entries=_lowerCAmelCase       )
         self.assertIsNone(_lowerCAmelCase       )

         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"		,  local_files_only=_lowerCAmelCase		,  _raise_exceptions_for_missing_entries=_lowerCAmelCase       )
         self.assertIsNone(_lowerCAmelCase       )

         UpperCAmelCase_											=mock.Mock()
         UpperCAmelCase_											=500
         UpperCAmelCase_											={}
         UpperCAmelCase_											=HTTPError
         UpperCAmelCase_											={}

         # Under the mock environment we get a 500 error when trying to reach the tokenizer.
         with mock.patch("requests.Session.request"		,  return_value=_lowerCAmelCase       ) as mock_head:
            UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"		,  _raise_exceptions_for_connection_errors=_lowerCAmelCase       )
            self.assertIsNone(_lowerCAmelCase       )
            # This check we did call the fake head request
            mock_head.assert_called()



      def 	lowerCAmelCase__    (	self:						Any       )						->    Tuple:
         '''simple docstring'''

         self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only"		,  _lowerCAmelCase       )       )
         self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"		,  _lowerCAmelCase       )       )
         self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"		,  _lowerCAmelCase       )       )



      def 	lowerCAmelCase__    (	self:						Any       )						->    Dict:
         '''simple docstring'''

         self.assertIsNone(get_file_from_repo("bert-base-cased"		,  "ahah.txt"       )       )

         # The function raises if the repository does not exist.
         with self.assertRaisesRegex(_lowerCAmelCase		,  "is not a valid model identifier"       ):
            get_file_from_repo("bert-base-case"		,  _lowerCAmelCase       )

         # The function raises if the revision does not exist.
         with self.assertRaisesRegex(_lowerCAmelCase		,  "is not a valid git identifier"       ):
            get_file_from_repo("bert-base-cased"		,  _lowerCAmelCase		,  revision="ahaha"       )

         UpperCAmelCase_											=get_file_from_repo("bert-base-cased"		,  _lowerCAmelCase       )
         # The name is the cached name which is not very easy to test, so instead we load the content.
         UpperCAmelCase_											=json.loads(open(_lowerCAmelCase		,  "r"       ).read()       )
         self.assertEqual(config["hidden_size"]		,  768       )






      def 	lowerCAmelCase__    (	self:						Optional[int]       )						->    Dict:
         '''simple docstring'''

         with tempfile.TemporaryDirectory() as tmp_dir:
            UpperCAmelCase_											=Path(_lowerCAmelCase       ) / "a.txt"
            filename.touch()
            self.assertEqual(get_file_from_repo(_lowerCAmelCase		,  "a.txt"       )		,  str(_lowerCAmelCase       )       )

            self.assertIsNone(get_file_from_repo(_lowerCAmelCase		,  "b.txt"       )       )




