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

import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory

from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
    convert,
    ensure_valid_input,
    generate_identified_filename,
    infer_shapes,
    quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow







class __snake_case       :




   def 			__a		(					self    :       str ,			_lowercase    :       str ,			_lowercase    :       Dict ,			_lowercase    :       List[Any]   ):



     """simple docstring"""






     return None







class __snake_case       :




   def 			__a		(					self    :       List[str] ,			_lowercase    :       List[str] ,			_lowercase    :       str ,			_lowercase    :       List[Any] ,			_lowercase    :       str   ):



     """simple docstring"""






     return None







class __snake_case       (		unittest.TestCase	):
   lowerCAmelCase_														=							[
       # (model_name, model_kwargs)
       ("bert-base-cased", {}),
       ("gpt2", {"use_cache": False}),  # We don't support exporting GPT2 past keys anymore
   ]




   @require_tf
   @slow
   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
       self._test_export(_lowercase ,			"""tf""" ,			12 ,			**_lowercase   )




   @require_torch
   @slow
   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






     for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
       self._test_export(_lowercase ,			"""pt""" ,			12 ,			**_lowercase   )




   @require_torch
   @slow
   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     from transformers import BertModel

     SCREAMING_SNAKE_CASE__    							=   ["""[UNK]""", """[SEP]""", """[CLS]""", """[PAD]""", """[MASK]""", """some""", """other""", """words"""]
     with NamedTemporaryFile(mode="""w+t"""   ) as vocab_file:
       vocab_file.write("""\n""".join(_lowercase   )   )
       vocab_file.flush()
       SCREAMING_SNAKE_CASE__    							=   BertTokenizerFast(vocab_file.name   )

     with TemporaryDirectory() as bert_save_dir:
       SCREAMING_SNAKE_CASE__    							=   BertModel(BertConfig(vocab_size=len(_lowercase   )   )   )
       model.save_pretrained(_lowercase   )
       self._test_export(_lowercase ,			"""pt""" ,			12 ,			_lowercase   )




   @require_tf
   @slow
   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
       SCREAMING_SNAKE_CASE__    							=   self._test_export(_lowercase ,			"""tf""" ,			12 ,			**_lowercase   )
       SCREAMING_SNAKE_CASE__    							=   quantize(Path(_lowercase   )   )

       # Ensure the actual quantized model is not bigger than the original one
       if quantized_path.stat().st_size >= Path(_lowercase   ).stat().st_size:
         self.fail("""Quantized model is bigger than initial ONNX model"""   )




   @require_torch
   @slow
   def 			__a		(					self    :       Any   ):



     """simple docstring"""






     for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
       SCREAMING_SNAKE_CASE__    							=   self._test_export(_lowercase ,			"""pt""" ,			12 ,			**_lowercase   )
       SCREAMING_SNAKE_CASE__    							=   quantize(_lowercase   )

       # Ensure the actual quantized model is not bigger than the original one
       if quantized_path.stat().st_size >= Path(_lowercase   ).stat().st_size:
         self.fail("""Quantized model is bigger than initial ONNX model"""   )




   def 			__a		(					self    :       Union[str, Any] ,			_lowercase    :       List[str] ,			_lowercase    :       Tuple ,			_lowercase    :       Optional[Any] ,			_lowercase    :       str=None ,			**_lowercase    :       List[str]   ):



     """simple docstring"""






     try:
       # Compute path
       with TemporaryDirectory() as tempdir:
         SCREAMING_SNAKE_CASE__    							=   Path(_lowercase   ).joinpath("""model.onnx"""   )

       # Remove folder if exists
       if path.parent.exists():
         path.parent.rmdir()

       # Export
       convert(_lowercase ,			_lowercase ,			_lowercase ,			_lowercase ,			_lowercase ,			**_lowercase   )

       return path
     except Exception as e:
       self.fail(_lowercase   )




   @require_torch
   @require_tokenizers
   @slow
   def 			__a		(					self    :       List[str]   ):



     """simple docstring"""






     from transformers import BertModel

     SCREAMING_SNAKE_CASE__    							=   BertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random"""   )   )
     SCREAMING_SNAKE_CASE__    							=   BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random"""   )
     self._test_infer_dynamic_axis(_lowercase ,			_lowercase ,			"""pt"""   )




   @require_tf
   @require_tokenizers
   @slow
   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     from transformers import TFBertModel

     SCREAMING_SNAKE_CASE__    							=   TFBertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random"""   )   )
     SCREAMING_SNAKE_CASE__    							=   BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random"""   )
     self._test_infer_dynamic_axis(_lowercase ,			_lowercase ,			"""tf"""   )




   def 			__a		(					self    :       List[Any] ,			_lowercase    :       List[Any] ,			_lowercase    :       Optional[int] ,			_lowercase    :       Dict   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   FeatureExtractionPipeline(_lowercase ,			_lowercase   )

     SCREAMING_SNAKE_CASE__    							=   ["""input_ids""", """token_type_ids""", """attention_mask""", """output_0""", """output_1"""]
     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   infer_shapes(_lowercase ,			_lowercase   )

     # Assert all variables are present
     self.assertEqual(len(_lowercase   ) ,			len(_lowercase   )   )
     self.assertTrue(all(var_name in shapes for var_name in variable_names   )   )
     self.assertSequenceEqual(variable_names[:3] ,			_lowercase   )
     self.assertSequenceEqual(variable_names[3:] ,			_lowercase   )

     # Assert inputs are {0: batch, 1: sequence}
     for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
       self.assertDictEqual(shapes[var_name] ,			{0: """batch""", 1: """sequence"""}   )

     # Assert outputs are {0: batch, 1: sequence} and {0: batch}
     self.assertDictEqual(shapes["""output_0"""] ,			{0: """batch""", 1: """sequence"""}   )
     self.assertDictEqual(shapes["""output_1"""] ,			{0: """batch"""}   )




   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   ["""input_ids""", """attention_mask""", """token_type_ids"""]
     SCREAMING_SNAKE_CASE__    							=   {"""input_ids""": [1, 2, 3, 4], """attention_mask""": [0, 0, 0, 0], """token_type_ids""": [1, 1, 1, 1]}
     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   ensure_valid_input(FuncContiguousArgs() ,			_lowercase ,			_lowercase   )

     # Should have exactly the same number of args (all are valid)
     self.assertEqual(len(_lowercase   ) ,			3   )

     # Should have exactly the same input names
     self.assertEqual(set(_lowercase   ) ,			set(_lowercase   )   )

     # Parameter should be reordered according to their respective place in the function:
     # (input_ids, token_type_ids, attention_mask)
     self.assertEqual(_lowercase ,			(tokens["""input_ids"""], tokens["""token_type_ids"""], tokens["""attention_mask"""])   )

     # Generated args are interleaved with another args (for instance parameter "past" in GPT2)
     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   ensure_valid_input(FuncNonContiguousArgs() ,			_lowercase ,			_lowercase   )

     # Should have exactly the one arg (all before the one not provided "some_other_args")
     self.assertEqual(len(_lowercase   ) ,			1   )
     self.assertEqual(len(_lowercase   ) ,			1   )

     # Should have only "input_ids"
     self.assertEqual(inputs_args[0] ,			tokens["""input_ids"""]   )
     self.assertEqual(ordered_input_names[0] ,			"""input_ids"""   )




   def 			__a		(					self    :       List[str]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   generate_identified_filename(Path("""/home/something/my_fake_model.onnx"""   ) ,			"""-test"""   )
     self.assertEqual("""/home/something/my_fake_model-test.onnx""" ,			generated.as_posix()   )
