






"""simple docstring"""
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()



class      SCREAMING_SNAKE_CASE  (				unittest.TestCase						):





	"""simple docstring"""




	@property
	def    lowerCamelCase(self							):
		torch.manual_seed(0							)
		A_		:						str	    =   UNetaDModel(
		    block_out_channels=(32, 64)     ,     layers_per_block=2     ,     sample_size=32     ,     in_channels=3     ,     out_channels=3     ,     down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")     ,     up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")     ,     )
		return model





	@property
	def    lowerCamelCase(self							):
		torch.manual_seed(0							)
		A_		:						Dict	    =   VQModel(
		    block_out_channels=[32, 64]     ,     in_channels=3     ,     out_channels=3     ,     down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]     ,     up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]     ,     latent_channels=3     ,     )
		return model





	@property
	def    lowerCamelCase(self							):
		torch.manual_seed(0							)
		A_		:						List[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=1000     ,     )
		return CLIPTextModel(lowerCAmelCase_							)





	def    lowerCamelCase(self							):
		A_		:						Optional[Any]	    =   self.dummy_uncond_unet
		A_		:						List[str]	    =   DDIMScheduler()
		A_		:						Optional[int]	    =   self.dummy_vq_model

		A_		:						Union[str, Any]	    =   LDMPipeline(unet=lowerCAmelCase_     ,     vqvae=lowerCAmelCase_     ,     scheduler=lowerCAmelCase_							)
		ldm.to(lowerCAmelCase_							)
		ldm.set_progress_bar_config(disable=lowerCAmelCase_							)

		A_		:						Optional[Any]	    =   torch.manual_seed(0							)
		A_		:						Any	    =   ldm(generator=lowerCAmelCase_     ,     num_inference_steps=2     ,     output_type="""numpy"""							).images

		A_		:						Optional[Any]	    =   torch.manual_seed(0							)
		A_		:						Any	    =   ldm(generator=lowerCAmelCase_     ,     num_inference_steps=2     ,     output_type="""numpy"""     ,     return_dict=lowerCAmelCase_							)[0]

		A_		:						Optional[int]	    =   image[0, -3:, -3:, -1]
		A_		:						List[str]	    =   image_from_tuple[0, -3:, -3:, -1]

		assert image.shape == (1, 64, 64, 3)
		A_		:						int	    =   np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172]							)
		A_		:						str	    =   1e-2 if torch_device != """mps""" else 3e-2

		assert np.abs(image_slice.flatten() - expected_slice							).max() < tolerance
		assert np.abs(image_from_tuple_slice.flatten() - expected_slice							).max() < tolerance






@slow
@require_torch
class      SCREAMING_SNAKE_CASE  (				unittest.TestCase						):





	"""simple docstring"""




	def    lowerCamelCase(self							):
		A_		:						Union[str, Any]	    =   LDMPipeline.from_pretrained("""CompVis/ldm-celebahq-256"""							)
		ldm.to(lowerCAmelCase_							)
		ldm.set_progress_bar_config(disable=lowerCAmelCase_							)

		A_		:						Union[str, Any]	    =   torch.manual_seed(0							)
		A_		:						Optional[int]	    =   ldm(generator=lowerCAmelCase_     ,     num_inference_steps=5     ,     output_type="""numpy"""							).images

		A_		:						Union[str, Any]	    =   image[0, -3:, -3:, -1]

		assert image.shape == (1, 256, 256, 3)
		A_		:						Optional[int]	    =   np.array([0.4399, 0.44975, 0.46825, 0.474, 0.4359, 0.4581, 0.45095, 0.4341, 0.4447]							)
		A_		:						List[str]	    =   1e-2 if torch_device != """mps""" else 3e-2

		assert np.abs(image_slice.flatten() - expected_slice							).max() < tolerance









"""simple docstring"""
import json
import os
from pathlib import Path

import pytest

from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadManager
from datasets.utils.file_utils import hash_url_to_filename


_lowerCAmelCase         =							"http://www.mocksite.com/file1.txt"
_lowerCAmelCase         =							"\"text\": [\"foo\", \"foo\"]"
_lowerCAmelCase         =							"6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8"



class      SCREAMING_SNAKE_CASE  :





	"""simple docstring"""




	_A       :				Optional[int]    =				200
	_A       :				Dict    =				{"""Content-Length""": """100"""}
	_A       :				List[Any]    =				{}





	def    lowerCamelCase(self     ,     **lowerCAmelCase_							):
		return [bytes(lowerCAmelCase_     ,     """utf-8"""							)]






def 			__UpperCamelCase	(		*snake_case__   ,   **snake_case__					):
	return MockResponse()






@pytest.mark.parametrize("""urls_type"""   ,   [str, list, dict]					)
def 			__UpperCamelCase	(		snake_case__   ,   snake_case__   ,   snake_case__					):
	import requests

	monkeypatch.setattr(snake_case__   ,   """request"""   ,   snake_case__					)

	A_		:						Optional[int]	    =   URL
	if issubclass(snake_case__   ,   snake_case__					):
		A_		:						str	    =   url
	elif issubclass(snake_case__   ,   snake_case__					):
		A_		:						Union[str, Any]	    =   [url]
	elif issubclass(snake_case__   ,   snake_case__					):
		A_		:						List[Any]	    =   {"""train""": url}
	A_		:						Tuple	    =   """dummy"""
	A_		:						List[str]	    =   """downloads"""
	A_		:						List[str]	    =   tmp_path
	A_		:						str	    =   DownloadConfig(
	    cache_dir=os.path.join(snake_case__   ,   snake_case__					)   ,   use_etag=snake_case__   ,   )
	A_		:						Any	    =   DownloadManager(dataset_name=snake_case__   ,   download_config=snake_case__					)
	A_		:						Dict	    =   dl_manager.download(snake_case__					)
	A_		:						List[str]	    =   urls
	for downloaded_paths in [downloaded_paths]:
		if isinstance(snake_case__   ,   snake_case__					):
			A_		:						Optional[Any]	    =   [downloaded_paths]
			A_		:						Tuple	    =   [urls]
		elif isinstance(snake_case__   ,   snake_case__					):
			assert "train" in downloaded_paths.keys()
			A_		:						Union[str, Any]	    =   downloaded_paths.values()
			A_		:						Tuple	    =   urls.values()
		assert downloaded_paths
		for downloaded_path, input_url in zip(snake_case__   ,   snake_case__					):
			assert downloaded_path == dl_manager.downloaded_paths[input_url]
			A_		:						Union[str, Any]	    =   Path(snake_case__					)
			A_		:						str	    =   downloaded_path.parts
			assert parts[-1] == HASH
			assert parts[-2] == cache_subdir
			assert downloaded_path.exists()
			A_		:						List[str]	    =   downloaded_path.read_text()
			assert content == CONTENT
			A_		:						Union[str, Any]	    =   downloaded_path.with_suffix(""".json"""					)
			assert metadata_downloaded_path.exists()
			A_		:						List[str]	    =   json.loads(metadata_downloaded_path.read_text()					)
			assert metadata_content == {"url": URL, "etag": None}






@pytest.mark.parametrize("""paths_type"""   ,   [str, list, dict]					)
def 			__UpperCamelCase	(		snake_case__   ,   snake_case__   ,   snake_case__					):
	A_		:						str	    =   str(snake_case__					)
	if issubclass(snake_case__   ,   snake_case__					):
		A_		:						List[str]	    =   filename
	elif issubclass(snake_case__   ,   snake_case__					):
		A_		:						Tuple	    =   [filename]
	elif issubclass(snake_case__   ,   snake_case__					):
		A_		:						Dict	    =   {"""train""": filename}
	A_		:						Union[str, Any]	    =   """dummy"""
	A_		:						Dict	    =   xz_file.parent
	A_		:						List[str]	    =   """extracted"""
	A_		:						int	    =   DownloadConfig(
	    cache_dir=snake_case__   ,   use_etag=snake_case__   ,   )
	A_		:						str	    =   DownloadManager(dataset_name=snake_case__   ,   download_config=snake_case__					)
	A_		:						int	    =   dl_manager.extract(snake_case__					)
	A_		:						int	    =   paths
	for extracted_paths in [extracted_paths]:
		if isinstance(snake_case__   ,   snake_case__					):
			A_		:						Dict	    =   [extracted_paths]
			A_		:						str	    =   [paths]
		elif isinstance(snake_case__   ,   snake_case__					):
			assert "train" in extracted_paths.keys()
			A_		:						Any	    =   extracted_paths.values()
			A_		:						str	    =   paths.values()
		assert extracted_paths
		for extracted_path, input_path in zip(snake_case__   ,   snake_case__					):
			assert extracted_path == dl_manager.extracted_paths[input_path]
			A_		:						str	    =   Path(snake_case__					)
			A_		:						List[str]	    =   extracted_path.parts
			assert parts[-1] == hash_url_to_filename(snake_case__   ,   etag=snake_case__					)
			assert parts[-2] == extracted_subdir
			assert extracted_path.exists()
			A_		:						Optional[Any]	    =   extracted_path.read_text()
			A_		:						Optional[int]	    =   text_file.read_text()
			assert extracted_file_content == expected_file_content






def 			__UpperCamelCase	(		snake_case__   ,   snake_case__					):
	assert path.endswith(""".jsonl"""					)
	for num_items, line in enumerate(snake_case__   ,   start=1					):
		A_		:						List[str]	    =   json.loads(line.decode("""utf-8"""					)					)
		assert item.keys() == {"col_1", "col_2", "col_3"}
	assert num_items == 4






@pytest.mark.parametrize("""archive_jsonl"""   ,   ["""tar_jsonl_path""", """zip_jsonl_path"""]					)
def 			__UpperCamelCase	(		snake_case__   ,   snake_case__					):
	A_		:						Optional[int]	    =   request.getfixturevalue(snake_case__					)
	A_		:						List[str]	    =   DownloadManager()
	for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(snake_case__					)   ,   start=1					):
		_test_jsonl(snake_case__   ,   snake_case__					)
	assert num_jsonl == 2






@pytest.mark.parametrize("""archive_nested_jsonl"""   ,   ["""tar_nested_jsonl_path""", """zip_nested_jsonl_path"""]					)
def 			__UpperCamelCase	(		snake_case__   ,   snake_case__					):
	A_		:						int	    =   request.getfixturevalue(snake_case__					)
	A_		:						Union[str, Any]	    =   DownloadManager()
	for num_tar, (path, file) in enumerate(dl_manager.iter_archive(snake_case__					)   ,   start=1					):
		for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(snake_case__					)   ,   start=1					):
			_test_jsonl(snake_case__   ,   snake_case__					)
	assert num_tar == 1
	assert num_jsonl == 2






def 			__UpperCamelCase	(		snake_case__					):
	A_		:						int	    =   DownloadManager()
	for num_file, file in enumerate(dl_manager.iter_files(snake_case__					)   ,   start=1					):
		assert os.path.basename(snake_case__					) == ("test.txt" if num_file == 1 else "train.txt")
	assert num_file == 2

