


'''simple docstring'''




import os
import zipfile

import pytest

from datasets.utils.extract import (
    BzipaExtractor,
    Extractor,
    GzipExtractor,
    LzaExtractor,
    SevenZipExtractor,
    TarExtractor,
    XzExtractor,
    ZipExtractor,
    ZstdExtractor,
)

from .utils import require_lza, require_pyazr, require_zstandard





@pytest.mark.parametrize(
    'compression_format, is_archive'							,   [
        ('7z', True),
        ('bz2', False),
        ('gzip', False),
        ('lz4', False),
        ('tar', True),
        ('xz', False),
        ('zip', True),
        ('zstd', False),
    ]							,   )
def   _a		(lowercase__			:   Optional[Any]							,   lowercase__			:   Optional[int]							,   lowercase__			:   int							,   lowercase__			:   Tuple							,   lowercase__			:   Dict							,   lowercase__			:   Tuple							,   lowercase__			:   List[str]							,   lowercase__			:   Dict							,   lowercase__			:   Optional[Any]							,   lowercase__			:   Any							,   lowercase__			:   List[str]							,   lowercase__			:   Any							,   )			->			Union[str, Any]:






     """simple docstring"""
     __snake_case           =						{
         '7z': (seven_zip_file, SevenZipExtractor),
         'bz2': (bza_file, BzipaExtractor),
         'gzip': (gz_file, GzipExtractor),
         'lz4': (lza_file, LzaExtractor),
         'tar': (tar_file, TarExtractor),
         'xz': (xz_file, XzExtractor),
         'zip': (zip_file, ZipExtractor),
         'zstd': (zstd_file, ZstdExtractor),
     }
     __snake_case      ,       __snake_case           =						input_paths_and_base_extractors[compression_format]
     if input_path is None:
          __snake_case           =						f'for \'{compression_format}\' compression_format, '
          if compression_format == "7z":
               reason += require_pyazr.kwargs["reason"]
          elif compression_format == "lz4":
               reason += require_lza.kwargs["reason"]
          elif compression_format == "zstd":
               reason += require_zstandard.kwargs["reason"]
          pytest.skip(lowercase__						)
     assert base_extractor.is_extractable(lowercase__						)
     __snake_case           =						tmp_path / ('extracted' if is_archive else 'extracted.txt')
     base_extractor.extract(lowercase__							,   lowercase__						)
     if is_archive:
          assert output_path.is_dir()
          for file_path in output_path.iterdir():
               assert file_path.name == text_file.name
               __snake_case           =						file_path.read_text(encoding='utf-8'						)
     else:
          __snake_case           =						output_path.read_text(encoding='utf-8'						)
     __snake_case           =						text_file.read_text(encoding='utf-8'						)
     assert extracted_file_content == expected_file_content





@pytest.mark.parametrize(
    'compression_format, is_archive'							,   [
        ('7z', True),
        ('bz2', False),
        ('gzip', False),
        ('lz4', False),
        ('tar', True),
        ('xz', False),
        ('zip', True),
        ('zstd', False),
    ]							,   )
def   _a		(lowercase__			:   Optional[Any]							,   lowercase__			:   str							,   lowercase__			:   Dict							,   lowercase__			:   int							,   lowercase__			:   List[str]							,   lowercase__			:   Tuple							,   lowercase__			:   Tuple							,   lowercase__			:   Optional[Any]							,   lowercase__			:   Optional[int]							,   lowercase__			:   Dict							,   lowercase__			:   Optional[int]							,   lowercase__			:   Union[str, Any]							,   )			->			Dict:






     """simple docstring"""
     __snake_case           =						{
         '7z': seven_zip_file,
         'bz2': bza_file,
         'gzip': gz_file,
         'lz4': lza_file,
         'tar': tar_file,
         'xz': xz_file,
         'zip': zip_file,
         'zstd': zstd_file,
     }
     __snake_case           =						input_paths[compression_format]
     if input_path is None:
          __snake_case           =						f'for \'{compression_format}\' compression_format, '
          if compression_format == "7z":
               reason += require_pyazr.kwargs["reason"]
          elif compression_format == "lz4":
               reason += require_lza.kwargs["reason"]
          elif compression_format == "zstd":
               reason += require_zstandard.kwargs["reason"]
          pytest.skip(lowercase__						)
     __snake_case           =						Extractor.infer_extractor_format(lowercase__						)
     assert extractor_format is not None
     __snake_case           =						tmp_path / ('extracted' if is_archive else 'extracted.txt')
     Extractor.extract(lowercase__							,   lowercase__							,   lowercase__						)
     if is_archive:
          assert output_path.is_dir()
          for file_path in output_path.iterdir():
               assert file_path.name == text_file.name
               __snake_case           =						file_path.read_text(encoding='utf-8'						)
     else:
          __snake_case           =						output_path.read_text(encoding='utf-8'						)
     __snake_case           =						text_file.read_text(encoding='utf-8'						)
     assert extracted_file_content == expected_file_content





@pytest.fixture
def   _a		(lowercase__			:   List[str]							,   lowercase__			:   Union[str, Any]						)			->			Any:






     """simple docstring"""
     import tarfile

     __snake_case           =						tmp_path / 'data_dot_dot'
     directory.mkdir()
     __snake_case           =						directory / 'tar_file_with_dot_dot.tar'
     with tarfile.TarFile(lowercase__							,   'w'						) as f:
          f.add(lowercase__							,   arcname=os.path.join('..'							,   text_file.name						)						)
     return path





@pytest.fixture
def   _a		(lowercase__			:   str						)			->			Dict:






     """simple docstring"""
     import tarfile

     __snake_case           =						tmp_path / 'data_sym_link'
     directory.mkdir()
     __snake_case           =						directory / 'tar_file_with_sym_link.tar'
     os.symlink('..'							,   directory / 'subdir'							,   target_is_directory=lowercase__						)
     with tarfile.TarFile(lowercase__							,   'w'						) as f:
          f.add(str(directory / 'subdir'						)							,   arcname='subdir'						)  # str required by os.readlink on Windows and Python < 3.8
     return path





@pytest.mark.parametrize(
    'insecure_tar_file, error_log'							,   [('tar_file_with_dot_dot', 'illegal path'), ('tar_file_with_sym_link', 'Symlink')]							,   )
def   _a		(lowercase__			:   List[Any]							,   lowercase__			:   List[Any]							,   lowercase__			:   List[Any]							,   lowercase__			:   Any							,   lowercase__			:   Optional[Any]							,   lowercase__			:   List[Any]						)			->			str:






     """simple docstring"""
     __snake_case           =						{
         'tar_file_with_dot_dot': tar_file_with_dot_dot,
         'tar_file_with_sym_link': tar_file_with_sym_link,
     }
     __snake_case           =						insecure_tar_files[insecure_tar_file]
     __snake_case           =						tmp_path / 'extracted'
     TarExtractor.extract(lowercase__							,   lowercase__						)
     assert caplog.text
     for record in caplog.records:
          assert record.levelname == "ERROR"
          assert error_log in record.msg





def   _a		(lowercase__			:   Dict						)			->			Union[str, Any]:






     """simple docstring"""
     # We should have less false positives than zipfile.is_zipfile
     # We do that by checking only the magic number
     __snake_case           =						tmpdir / 'not_a_zip_file'
     # From: https://github.com/python/cpython/pull/5053
     __snake_case           =						(
         B'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00'
         B'\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6\'\x00\x00\x00\x15I'
         B'DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07'
         B'\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82'
     )
     with not_a_zip_file.open('wb'						) as f:
          f.write(lowercase__						)
     assert zipfile.is_zipfile(str(lowercase__						)						)  # is a false positive for `zipfile`
     assert not ZipExtractor.is_extractable(lowercase__						)  # but we're right









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        lowerCAmelCase__					(  _lowerCamelCase ,				unittest.TestCase       ):
				A_   :     int								=     VideoToVideoSDPipeline
				A_   :     Optional[Any]								=     TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'}       ) - {'image', 'width', 'height'}
				A_   :     List[str]								=     TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'}       ) - {'image'}
				A_   :     Tuple								=     PipelineTesterMixin.required_optional_params - {'latents'}
				A_   :     Dict								=     False

				# No `output_type`.
				A_   :     str								=     frozenset(
				    [
				        'num_inference_steps',
				        'generator',
				        'latents',
				        'return_dict',
				        'callback',
				        'callback_steps',
				    ]       )


				def __UpperCamelCase						(							self      :  Optional[int]       )		->     List[Any]:
											torch.manual_seed(0       )
											A      						=    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						, )
											A      						=    DDIMScheduler(
											    beta_start=0.0_0_0_8_5						, beta_end=0.0_1_2						, beta_schedule='scaled_linear'						, clip_sample=__UpperCamelCase						, set_alpha_to_one=__UpperCamelCase						, )
											torch.manual_seed(0       )
											A      						=    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       )
											A      						=    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=1_000						, hidden_act='gelu'						, projection_dim=512						, )
											A      						=    CLIPTextModel(__UpperCamelCase       )
											A      						=    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'       )

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


				def __UpperCamelCase						(							self      :  Optional[Any]						, __UpperCamelCase      :  Any						, __UpperCamelCase      :  str=0       )		->     Optional[int]:
											# 3 frames
											A      						=    floats_tensor((1, 3, 3, 32, 32)						, rng=random.Random(__UpperCamelCase       )       ).to(__UpperCamelCase       )

											if str(__UpperCamelCase       ).startswith('mps'       ):
																		A      						=    torch.manual_seed(__UpperCamelCase       )
											else:
																		A      						=    torch.Generator(device=__UpperCamelCase       ).manual_seed(__UpperCamelCase       )
											A      						=    {
											    '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 __UpperCamelCase						(							self      :  Optional[int]       )		->     str:
											A      						=    'cpu'  # ensure determinism for the device-dependent torch.Generator
											A      						=    self.get_dummy_components()
											A      						=    VideoToVideoSDPipeline(**__UpperCamelCase       )
											A      						=    sd_pipe.to(__UpperCamelCase       )
											sd_pipe.set_progress_bar_config(disable=__UpperCamelCase       )

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

											assert frames[0].shape == (32, 32, 3)
											A      						=    np.array([106, 117, 113, 174, 137, 112, 148, 151, 131]       )

											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 __UpperCamelCase						(							self      :  int       )		->     Tuple:
											self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__UpperCamelCase						, expected_max_diff=5e-3       )


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


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


				@unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.'       )
				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Optional[Any]:
											pass


				def __UpperCamelCase						(							self      :  Any       )		->     Any:
											return super().test_progress_bar()





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


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     Dict:
											A      						=    VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL'						, torch_dtype=torch.floataa       )
											pipe.enable_model_cpu_offload()

											# 10 frames
											A      						=    torch.Generator(device='cpu'       ).manual_seed(0       )
											A      						=    torch.randn((1, 10, 3, 1_024, 576)						, generator=__UpperCamelCase       )
											A      						=    video.to('cuda'       )

											A      						=    'Spiderman is surfing'

											A      						=    pipe(__UpperCamelCase						, video=__UpperCamelCase						, generator=__UpperCamelCase						, num_inference_steps=3						, output_type='pt'       ).frames

											A      						=    np.array([-1.0_4_5_8_9_8_4, -1.1_2_7_9_2_9_7, -0.9_6_6_3_0_8_6, -0.9_1_5_0_3_9_0_6, -0.7_5_0_9_7_6_5_6]       )
											assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array       ).sum() < 1e-2