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

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


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								torch.manual_seed(0						)
								_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					,     )
								_snake_case     		=	DDIMScheduler(
								    beta_start=0.00085					,     beta_end=0.012					,     beta_schedule='scaled_linear'					,     clip_sample=lowerCAmelCase__					,     set_alpha_to_one=lowerCAmelCase__					,     )
								torch.manual_seed(0						)
								_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						)
								_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					,     )
								_snake_case     		=	CLIPTextModel(lowerCAmelCase__						)
								_snake_case     		=	CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'						)

								_snake_case     		=	{
								    'unet': unet,
								    'scheduler': scheduler,
								    'vae': vae,
								    'text_encoder': text_encoder,
								    'tokenizer': tokenizer,
								}
								return components


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_=0						):





								"""simple docstring"""






								_snake_case     		=	floats_tensor((1, 3, 3, 32, 32)					,     rng=random.Random(lowerCAmelCase__						)						).to(lowerCAmelCase__						)

								if str(lowerCAmelCase__						).startswith('mps'						):
									_snake_case     		=	torch.manual_seed(lowerCAmelCase__						)
								else:
									_snake_case     		=	torch.Generator(device=lowerCAmelCase__						).manual_seed(lowerCAmelCase__						)
								_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 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	'cpu'  # ensure determinism for the device-dependent torch.Generator
								_snake_case     		=	self.get_dummy_components()
								_snake_case     		=	VideoToVideoSDPipeline(**lowerCAmelCase__						)
								_snake_case     		=	sd_pipe.to(lowerCAmelCase__						)
								sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__						)

								_snake_case     		=	self.get_dummy_inputs(lowerCAmelCase__						)
								_snake_case     		=	'np'
								_snake_case     		=	sd_pipe(**lowerCAmelCase__						).frames
								_snake_case     		=	frames[0][-3:, -3:, -1]

								assert frames[0].shape == (32, 32, 3)
								_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 				lowerCamelCase       ( self						):





								"""simple docstring"""






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


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





								"""simple docstring"""






								pass


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





								"""simple docstring"""






								pass


							@unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.'						)
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								pass




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								return super().test_progress_bar()


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


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL'					,     torch_dtype=torch.floataa						)
								pipe.enable_model_cpu_offload()

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

								_snake_case     		=	'Spiderman is surfing'

								_snake_case     		=	pipe(lowerCAmelCase__					,     video=lowerCAmelCase__					,     generator=lowerCAmelCase__					,     num_inference_steps=3					,     output_type='pt'						).frames

								_snake_case     		=	np.array([-1.0458984, -1.1279297, -0.9663086, -0.91503906, -0.75097656]						)
								assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array						).sum() < 1E-2



'''simple docstring'''







import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowercase					:							str   =      version.parse(importlib_metadata.version("nltk"))
if NLTK_VERSION >= version.Version("3.6.4"):
					from nltk import word_tokenize


lowercase					:							int   =      "\\n@inproceedings{banarjee2005,\n  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n  author    = {Banerjee, Satanjeev  and Lavie, Alon},\n  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n  month     = jun,\n  year      = {2005},\n  address   = {Ann Arbor, Michigan},\n  publisher = {Association for Computational Linguistics},\n  url       = {https://www.aclweb.org/anthology/W05-0909},\n  pages     = {65--72},\n}\n"

lowercase					:							Any   =      "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n"

lowercase					:							Optional[Any]   =      "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n    gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n    'meteor': meteor score.\nExamples:\n\n    >>> meteor = datasets.load_metric('meteor')\n    >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n    >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n    >>> results = meteor.compute(predictions=predictions, references=references)\n    >>> print(round(results[\"meteor\"], 4))\n    0.6944\n"


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


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py']					,     reference_urls=[
								        'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score',
								        'https://en.wikipedia.org/wiki/METEOR',
								    ]					,     )


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_						):





								"""simple docstring"""






								import nltk

								nltk.download('wordnet'						)
								if NLTK_VERSION >= version.Version('3.6.5'						):
									nltk.download('punkt'						)
								if NLTK_VERSION >= version.Version('3.6.6'						):
									nltk.download('omw-1.4'						)




							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_=0.9					,     lowerCAmelCase_=3					,     lowerCAmelCase_=0.5						):





								"""simple docstring"""






								if NLTK_VERSION >= version.Version('3.6.5'						):
									_snake_case     		=	[
									    meteor_score.single_meteor_score(
									        word_tokenize(lowerCAmelCase_						)					,     word_tokenize(lowerCAmelCase_						)					,     alpha=lowerCAmelCase_					,     beta=lowerCAmelCase_					,     gamma=lowerCAmelCase_						)
									    for ref, pred in zip(lowerCAmelCase_					,     lowerCAmelCase_						)
									]
								else:
									_snake_case     		=	[
									    meteor_score.single_meteor_score(lowerCAmelCase_					,     lowerCAmelCase_					,     alpha=lowerCAmelCase_					,     beta=lowerCAmelCase_					,     gamma=lowerCAmelCase_						)
									    for ref, pred in zip(lowerCAmelCase_					,     lowerCAmelCase_						)
									]

								return {"meteor": np.mean(lowerCAmelCase_						)}

