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


       def 	_snake_case				(    self				)						->    int:
              torch.manual_seed(0				)
              SCREAMING_SNAKE_CASE_							:				int		=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_							:				Dict		=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				)
              SCREAMING_SNAKE_CASE_							:				Optional[Any]		=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				)
              SCREAMING_SNAKE_CASE_							:				Optional[Any]		=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						,       )
              SCREAMING_SNAKE_CASE_							:				str		=CLIPTextModel(__A				)
              SCREAMING_SNAKE_CASE_							:				Optional[Any]		=CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

              SCREAMING_SNAKE_CASE_							:				List[str]		={
                  '''unet''': unet,
                  '''scheduler''': scheduler,
                  '''vae''': vae,
                  '''text_encoder''': text_encoder,
                  '''tokenizer''': tokenizer,
              }
              return components


       def 	_snake_case				(    self						,       __A						,       __A=0				)						->    Optional[Any]:
              if str(__A				).startswith('''mps'''				):
                     SCREAMING_SNAKE_CASE_							:				Optional[Any]		=torch.manual_seed(__A				)
              else:
                     SCREAMING_SNAKE_CASE_							:				Tuple		=torch.Generator(device=__A				).manual_seed(__A				)
              SCREAMING_SNAKE_CASE_							:				Tuple		={
                  '''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 	_snake_case				(    self				)						->    List[str]:
              SCREAMING_SNAKE_CASE_							:				Any		='''cpu'''  # ensure determinism for the device-dependent torch.Generator
              SCREAMING_SNAKE_CASE_							:				Optional[Any]		=self.get_dummy_components()
              SCREAMING_SNAKE_CASE_							:				Dict		=TextToVideoSDPipeline(**__A				)
              SCREAMING_SNAKE_CASE_							:				str		=sd_pipe.to(__A				)
              sd_pipe.set_progress_bar_config(disable=__A				)

              SCREAMING_SNAKE_CASE_							:				int		=self.get_dummy_inputs(__A				)
              SCREAMING_SNAKE_CASE_							:				List[Any]		='''np'''
              SCREAMING_SNAKE_CASE_							:				List[str]		=sd_pipe(**__A				).frames
              SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=frames[0][-3:, -3:, -1]

              assert frames[0].shape == (64, 64, 3)
              SCREAMING_SNAKE_CASE_							:				List[str]		=np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0]				)

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


       def 	_snake_case				(    self				)						->    Optional[Any]:
              self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__A						,       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 	_snake_case				(    self				)						->    Tuple:
              self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__A						,       expected_max_diff=1e-2				)


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


       @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.'''				)
       def 	_snake_case				(    self				)						->    int:
              pass


       @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.'''				)
       def 	_snake_case				(    self				)						->    List[str]:
              pass





       def 	_snake_case				(    self				)						->    Optional[Any]:
              return super().test_progress_bar()






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


       def 	_snake_case				(    self				)						->    Union[str, Any]:
              SCREAMING_SNAKE_CASE_							:				Optional[Any]		=load_numpy(
                  '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy'''				)

              SCREAMING_SNAKE_CASE_							:				int		=TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b'''				)
              SCREAMING_SNAKE_CASE_							:				Dict		=DPMSolverMultistepScheduler.from_config(pipe.scheduler.config				)
              SCREAMING_SNAKE_CASE_							:				Dict		=pipe.to('''cuda'''				)

              SCREAMING_SNAKE_CASE_							:				Tuple		='''Spiderman is surfing'''
              SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=torch.Generator(device='''cpu'''				).manual_seed(0				)

              SCREAMING_SNAKE_CASE_							:				Tuple		=pipe(__A						,       generator=__A						,       num_inference_steps=25						,       output_type='''pt'''				).frames
              SCREAMING_SNAKE_CASE_							:				Tuple		=video_frames.cpu().numpy()

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





       def 	_snake_case				(    self				)						->    int:
              SCREAMING_SNAKE_CASE_							:				List[str]		=load_numpy(
                  '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy'''				)

              SCREAMING_SNAKE_CASE_							:				str		=TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b'''				)
              SCREAMING_SNAKE_CASE_							:				Any		=pipe.to('''cuda'''				)

              SCREAMING_SNAKE_CASE_							:				Dict		='''Spiderman is surfing'''
              SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=torch.Generator(device='''cpu'''				).manual_seed(0				)

              SCREAMING_SNAKE_CASE_							:				Optional[int]		=pipe(__A						,       generator=__A						,       num_inference_steps=2						,       output_type='''pt'''				).frames
              SCREAMING_SNAKE_CASE_							:				List[str]		=video_frames.cpu().numpy()

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


import absl  # noqa: F401 # Here to have a nice missing dependency error message early on
import nltk  # noqa: F401 # Here to have a nice missing dependency error message early on
import numpy  # noqa: F401 # Here to have a nice missing dependency error message early on
import six  # noqa: F401 # Here to have a nice missing dependency error message early on
from rouge_score import rouge_scorer, scoring

import datasets


_lowercase											=    """\
@inproceedings{lin-2004-rouge,
    title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",
    author = \"Lin, Chin-Yew\",
    booktitle = \"Text Summarization Branches Out\",
    month = jul,
    year = \"2004\",
    address = \"Barcelona, Spain\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W04-1013\",
    pages = \"74--81\",
}
"""

_lowercase											=    """\
ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for
evaluating automatic summarization and machine translation software in natural language processing.
The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.

Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.

This metrics is a wrapper around Google Research reimplementation of ROUGE:
https://github.com/google-research/google-research/tree/master/rouge
"""

_lowercase											=    """
Calculates average rouge scores for a list of hypotheses and references
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    rouge_types: A list of rouge types to calculate.
        Valid names:
        `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,
        `\"rougeL\"`: Longest common subsequence based scoring.
        `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.
        See details in https://github.com/huggingface/datasets/issues/617
    use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.
    use_aggregator: Return aggregates if this is set to True
Returns:
    rouge1: rouge_1 (precision, recall, f1),
    rouge2: rouge_2 (precision, recall, f1),
    rougeL: rouge_l (precision, recall, f1),
    rougeLsum: rouge_lsum (precision, recall, f1)
Examples:

    >>> rouge = datasets.load_metric('rouge')
    >>> predictions = [\"hello there\", \"general kenobi\"]
    >>> references = [\"hello there\", \"general kenobi\"]
    >>> results = rouge.compute(predictions=predictions, references=references)
    >>> print(list(results.keys()))
    ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']
    >>> print(results[\"rouge1\"])
    AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))
    >>> print(results[\"rouge1\"].mid.fmeasure)
    1.0
"""


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,      _KWARGS_DESCRIPTION       )
class 			lowercase_		(      datasets.Metric       ):


       def 	_snake_case				(    self				)						->    Union[str, Any]:
              return datasets.MetricInfo(
                  description=_DESCRIPTION						,       citation=_CITATION						,       inputs_description=_KWARGS_DESCRIPTION						,       features=datasets.Features(
                      {
                          '''predictions''': datasets.Value('''string'''						,       id='''sequence'''				),
                          '''references''': datasets.Value('''string'''						,       id='''sequence'''				),
                      }				)						,       codebase_urls=['''https://github.com/google-research/google-research/tree/master/rouge''']						,       reference_urls=[
                      '''https://en.wikipedia.org/wiki/ROUGE_(metric)''',
                      '''https://github.com/google-research/google-research/tree/master/rouge''',
                  ]						,       )





       def 	_snake_case				(    self						,       __A						,       __A						,       __A=None						,       __A=True						,       __A=False				)						->    List[str]:
              if rouge_types is None:
                     SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=['''rouge1''', '''rouge2''', '''rougeL''', '''rougeLsum''']

              SCREAMING_SNAKE_CASE_							:				Tuple		=rouge_scorer.RougeScorer(rouge_types=__A						,       use_stemmer=__A				)
              if use_aggregator:
                     SCREAMING_SNAKE_CASE_							:				List[str]		=scoring.BootstrapAggregator()
              else:
                     SCREAMING_SNAKE_CASE_							:				Tuple		=[]

              for ref, pred in zip(__A						,       __A				):
                     SCREAMING_SNAKE_CASE_							:				int		=scorer.score(__A						,       __A				)
                     if use_aggregator:
                            aggregator.add_scores(__A				)
                     else:
                            scores.append(__A				)

              if use_aggregator:
                     SCREAMING_SNAKE_CASE_							:				Tuple		=aggregator.aggregate()
              else:
                     SCREAMING_SNAKE_CASE_							:				Optional[int]		={}
                     for key in scores[0]:
                            SCREAMING_SNAKE_CASE_							:				Tuple		=[score[key] for score in scores]

              return result
