





import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile, rmtree
from typing import Generator

import datasets.config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.filelock import logger as fl_logger
from datasets.utils.info_utils import VerificationMode
from datasets.utils.logging import ERROR, get_logger


__lowerCAmelCase 	=      get_logger(__name__)

def      a    (   _lowercase :  List[str]							)  ->List[Any]:
		return TestCommand(
		    args.dataset			,    args.name			,    args.cache_dir			,    args.data_dir			,    args.all_configs			,    args.save_info or args.save_infos			,    args.ignore_verifications			,    args.force_redownload			,    args.clear_cache			,    )




class 	_UpperCAmelCase						( _lowercase       ):
					__A        = False  # to tell pytest it's not a test class




					@staticmethod
					def 						snake_case_		(    __lowerCAmelCase							)    ->	Any:
							UpperCamelCase__								=						parser.add_parser("""test"""     ,   help="""Test dataset implementation."""							)
							test_parser.add_argument("""--name"""     ,   type=__lowerCAmelCase     ,   default=__lowerCAmelCase     ,   help="""Dataset processing name"""							)
							test_parser.add_argument(
							    """--cache_dir"""     ,   type=__lowerCAmelCase     ,   default=__lowerCAmelCase     ,   help="""Cache directory where the datasets are stored."""     ,   )
							test_parser.add_argument(
							    """--data_dir"""     ,   type=__lowerCAmelCase     ,   default=__lowerCAmelCase     ,   help="""Can be used to specify a manual directory to get the files from."""     ,   )
							test_parser.add_argument("""--all_configs"""     ,   action="""store_true"""     ,   help="""Test all dataset configurations"""							)
							test_parser.add_argument(
							    """--save_info"""     ,   action="""store_true"""     ,   help="""Save the dataset infos in the dataset card (README.md)"""							)
							test_parser.add_argument(
							    """--ignore_verifications"""     ,   action="""store_true"""     ,   help="""Run the test without checksums and splits checks."""     ,   )
							test_parser.add_argument("""--force_redownload"""     ,   action="""store_true"""     ,   help="""Force dataset redownload"""							)
							test_parser.add_argument(
							    """--clear_cache"""     ,   action="""store_true"""     ,   help="""Remove downloaded files and cached datasets after each config test"""     ,   )
							# aliases
							test_parser.add_argument("""--save_infos"""     ,   action="""store_true"""     ,   help="""alias to save_info"""							)
							test_parser.add_argument("""dataset"""     ,   type=__lowerCAmelCase     ,   help="""Name of the dataset to download"""							)
							test_parser.set_defaults(func=_test_command_factory							)




					def __init__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   )    ->	int:
							UpperCamelCase__								=						dataset
							UpperCamelCase__								=						name
							UpperCamelCase__								=						cache_dir
							UpperCamelCase__								=						data_dir
							UpperCamelCase__								=						all_configs
							UpperCamelCase__								=						save_infos
							UpperCamelCase__								=						ignore_verifications
							UpperCamelCase__								=						force_redownload
							UpperCamelCase__								=						clear_cache
							if clear_cache and not cache_dir:
									print(
									    """When --clear_cache is used, specifying a cache directory is mandatory.\n"""
									    """The 'download' folder of the cache directory and the dataset builder cache will be deleted after each configuration test.\n"""
									    """Please provide a --cache_dir that will be used to test the dataset script."""							)
									exit(1							)
							if save_infos:
									UpperCamelCase__								=						True




					def 						snake_case_		(    self							)    ->	Tuple:
							fl_logger().setLevel(__lowerCAmelCase							)
							if self._name is not None and self._all_configs:
									print("""Both parameters `config` and `all_configs` can't be used at once."""							)
									exit(1							)
							UpperCamelCase__	,      UpperCamelCase__								=						self._dataset, self._name
							UpperCamelCase__								=						dataset_module_factory(__lowerCAmelCase							)
							UpperCamelCase__								=						import_main_class(module.module_path							)
							UpperCamelCase__								=						len(builder_cls.BUILDER_CONFIGS							) if self._all_configs and builder_cls.BUILDER_CONFIGS else 1

							def get_builders() -> Generator[DatasetBuilder, None, None]:
									if self._all_configs and builder_cls.BUILDER_CONFIGS:
											for i, config in enumerate(builder_cls.BUILDER_CONFIGS							):
													if "config_name" in module.builder_kwargs:
															yield builder_cls(
															    cache_dir=self._cache_dir     ,   data_dir=self._data_dir     ,   **module.builder_kwargs     ,   )
													else:
															yield builder_cls(
															    config_name=config.name     ,   cache_dir=self._cache_dir     ,   data_dir=self._data_dir     ,   **module.builder_kwargs     ,   )
									else:
											if "config_name" in module.builder_kwargs:
													yield builder_cls(cache_dir=self._cache_dir     ,   data_dir=self._data_dir     ,   **module.builder_kwargs							)
											else:
													yield builder_cls(
													    config_name=__lowerCAmelCase     ,   cache_dir=self._cache_dir     ,   data_dir=self._data_dir     ,   **module.builder_kwargs     ,   )

							for j, builder in enumerate(get_builders()							):
									print(F"""Testing builder '{builder.config.name}' ({j + 1}/{n_builders})"""							)
									UpperCamelCase__								=						os.path.exists(
									    os.path.join(builder.get_imported_module_dir()     ,   datasets.config.DATASETDICT_INFOS_FILENAME							)							)  # record checksums only if we need to update a (deprecated) dataset_infos.json
									builder.download_and_prepare(
									    download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
									    if not self._force_redownload
									    else DownloadMode.FORCE_REDOWNLOAD     ,   verification_mode=VerificationMode.NO_CHECKS
									    if self._ignore_verifications
									    else VerificationMode.ALL_CHECKS     ,   try_from_hf_gcs=__lowerCAmelCase     ,   )
									builder.as_dataset()
									if self._save_infos:
											builder._save_infos()

									# If save_infos=True, the dataset card (README.md) is created next to the loaded module file.
									# The dataset_infos are saved in the YAML part of the README.md

									# Let's move it to the original directory of the dataset script, to allow the user to
									# upload them on S3 at the same time afterwards.
									if self._save_infos:
											UpperCamelCase__								=						os.path.join(builder_cls.get_imported_module_dir()     ,   """README.md"""							)
											UpperCamelCase__								=						Path(__lowerCAmelCase							).name + """.py"""
											UpperCamelCase__								=						os.path.join(__lowerCAmelCase     ,   __lowerCAmelCase							)
											if os.path.isfile(__lowerCAmelCase							):
													UpperCamelCase__								=						os.path.dirname(__lowerCAmelCase							)
											elif os.path.isfile(__lowerCAmelCase							):
													UpperCamelCase__								=						path
											elif os.path.isdir(__lowerCAmelCase							):  # for local directories containing only data files
													UpperCamelCase__								=						path
											else:  # in case of a remote dataset
													UpperCamelCase__								=						None
													print(F"""Dataset card saved at {dataset_readme_path}"""							)

											# Move dataset_info back to the user
											if dataset_dir is not None:
													UpperCamelCase__								=						os.path.join(__lowerCAmelCase     ,   """README.md"""							)
													copyfile(__lowerCAmelCase     ,   __lowerCAmelCase							)
													print(F"""Dataset card saved at {user_dataset_readme_path}"""							)

            # If clear_cache=True, the download folder and the dataset builder cache directory are deleted
									if self._clear_cache:
											if os.path.isdir(builder._cache_dir							):
													logger.warning(F"""Clearing cache at {builder._cache_dir}"""							)
													rmtree(builder._cache_dir							)
											UpperCamelCase__								=						os.path.join(self._cache_dir     ,   datasets.config.DOWNLOADED_DATASETS_DIR							)
											if os.path.isdir(__lowerCAmelCase							):
													logger.warning(F"""Clearing cache at {download_dir}"""							)
													rmtree(__lowerCAmelCase							)

							print("""Test successful."""							)












import unittest

import torch

from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, slow, torch_device

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin




class 	_UpperCAmelCase						( _lowercase			,							_lowercase			,							unittest.TestCase       ):
					__A        = UNetaDModel
					__A        = "sample"




					@property
					def 						snake_case_		(    self							)    ->	Any:
							UpperCamelCase__								=						4
							UpperCamelCase__								=						14
							UpperCamelCase__								=						16

							UpperCamelCase__								=						floats_tensor((batch_size, num_features, seq_len)							).to(__lowerCAmelCase							)
							UpperCamelCase__								=						torch.tensor([10] * batch_size							).to(__lowerCAmelCase							)

							return {"sample": noise, "timestep": time_step}




					@property
					def 						snake_case_		(    self							)    ->	Optional[int]:
							return (4, 14, 16)




					@property
					def 						snake_case_		(    self							)    ->	Any:
							return (4, 14, 16)




					def 						snake_case_		(    self							)    ->	Any:
							pass




					def 						snake_case_		(    self							)    ->	Tuple:
							pass




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Any:
							super().test_determinism()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	int:
							super().test_outputs_equivalence()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Optional[Any]:
							super().test_from_save_pretrained()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							super().test_from_save_pretrained_variant()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Optional[int]:
							super().test_model_from_pretrained()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Dict:
							super().test_output()




					def 						snake_case_		(    self							)    ->	int:
							UpperCamelCase__								=						{
							    """block_out_channels""": (32, 64, 128, 256),
							    """in_channels""": 14,
							    """out_channels""": 14,
							    """time_embedding_type""": """positional""",
							    """use_timestep_embedding""": True,
							    """flip_sin_to_cos""": False,
							    """freq_shift""": 1.0,
							    """out_block_type""": """OutConv1DBlock""",
							    """mid_block_type""": """MidResTemporalBlock1D""",
							    """down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""),
							    """up_block_types""": ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D"""),
							    """act_fn""": """mish""",
							}
							UpperCamelCase__								=						self.dummy_input
							return init_dict, inputs_dict




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	List[Any]:
							UpperCamelCase__	,      UpperCamelCase__								=						UNetaDModel.from_pretrained(
							    """bglick13/hopper-medium-v2-value-function-hor32"""     ,   output_loading_info=__lowerCAmelCase     ,   subfolder="""unet"""							)
							self.assertIsNotNone(__lowerCAmelCase							)
							self.assertEqual(len(loading_info["""missing_keys"""]							)     ,   0							)

							model.to(__lowerCAmelCase							)
							UpperCamelCase__								=						model(**self.dummy_input							)

							assert image is not None, "Make sure output is not None"




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Optional[Any]:
							UpperCamelCase__								=						UNetaDModel.from_pretrained("""bglick13/hopper-medium-v2-value-function-hor32"""     ,   subfolder="""unet"""							)
							torch.manual_seed(0							)
							if torch.cuda.is_available():
									torch.cuda.manual_seed_all(0							)

							UpperCamelCase__								=						model.config.in_channels
							UpperCamelCase__								=						16
							UpperCamelCase__								=						torch.randn((1, seq_len, num_features)							).permute(
							    0     ,   2     ,   1							)  # match original, we can update values and remove
							UpperCamelCase__								=						torch.full((num_features,)     ,   0							)

							with torch.no_grad():
									UpperCamelCase__								=						model(__lowerCAmelCase     ,   __lowerCAmelCase							).sample.permute(0     ,   2     ,   1							)

							UpperCamelCase__								=						output[0, -3:, -3:].flatten()
							# fmt: off
							UpperCamelCase__								=						torch.tensor([-2.1_3_7_1_7_2, 1.1_4_2_6_0_1_6, 0.3_6_8_8_6_8_7, -0.7_6_6_9_2_2, 0.7_3_0_3_1_4_6, 0.1_1_0_3_8_8_6_4, -0.4_7_6_0_6_3_3, 0.1_3_2_7_0_1_7_2, 0.0_2_5_9_1_3_4_8]							)
							# fmt: on
							self.assertTrue(torch.allclose(__lowerCAmelCase     ,   __lowerCAmelCase     ,   rtol=1E-3							)							)




					def 						snake_case_		(    self							)    ->	int:
							# Not implemented yet for this UNet
							pass




					@slow
					def 						snake_case_		(    self							)    ->	Tuple:
							UpperCamelCase__								=						"""harmonai/maestro-150k"""
							UpperCamelCase__								=						UNetaDModel.from_pretrained(__lowerCAmelCase     ,   subfolder="""unet"""							)
							model.to(__lowerCAmelCase							)

							UpperCamelCase__								=						65_536
							UpperCamelCase__								=						torch.sin(torch.arange(__lowerCAmelCase							)[None, None, :].repeat(1     ,   2     ,   1							)							).to(__lowerCAmelCase							)
							UpperCamelCase__								=						torch.tensor([1]							).to(__lowerCAmelCase							)

							with torch.no_grad():
									UpperCamelCase__								=						model(__lowerCAmelCase     ,   __lowerCAmelCase							).sample

							UpperCamelCase__								=						output.abs().sum()
							UpperCamelCase__								=						output.abs().max()

							assert (output_sum - 2_2_4.0_8_9_6).abs() < 0.5
							assert (output_max - 0.0_6_0_7).abs() < 4E-4




class 	_UpperCAmelCase						( _lowercase			,							_lowercase			,							unittest.TestCase       ):
					__A        = UNetaDModel
					__A        = "sample"




					@property
					def 						snake_case_		(    self							)    ->	Any:
							UpperCamelCase__								=						4
							UpperCamelCase__								=						14
							UpperCamelCase__								=						16

							UpperCamelCase__								=						floats_tensor((batch_size, num_features, seq_len)							).to(__lowerCAmelCase							)
							UpperCamelCase__								=						torch.tensor([10] * batch_size							).to(__lowerCAmelCase							)

							return {"sample": noise, "timestep": time_step}




					@property
					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							return (4, 14, 16)




					@property
					def 						snake_case_		(    self							)    ->	List[Any]:
							return (4, 14, 1)




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Dict:
							super().test_determinism()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Optional[int]:
							super().test_outputs_equivalence()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Optional[int]:
							super().test_from_save_pretrained()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Optional[Any]:
							super().test_from_save_pretrained_variant()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Optional[Any]:
							super().test_model_from_pretrained()




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	List[str]:
							# UNetRL is a value-function is different output shape
							UpperCamelCase__	,      UpperCamelCase__								=						self.prepare_init_args_and_inputs_for_common()
							UpperCamelCase__								=						self.model_class(**__lowerCAmelCase							)
							model.to(__lowerCAmelCase							)
							model.eval()

							with torch.no_grad():
									UpperCamelCase__								=						model(**__lowerCAmelCase							)

									if isinstance(__lowerCAmelCase     ,   __lowerCAmelCase							):
											UpperCamelCase__								=						output.sample

							self.assertIsNotNone(__lowerCAmelCase							)
							UpperCamelCase__								=						torch.Size((inputs_dict["""sample"""].shape[0], 1)							)
							self.assertEqual(output.shape     ,   __lowerCAmelCase     ,   """Input and output shapes do not match"""							)




					def 						snake_case_		(    self							)    ->	Optional[int]:
							pass




					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							pass




					def 						snake_case_		(    self							)    ->	Dict:
							UpperCamelCase__								=						{
							    """in_channels""": 14,
							    """out_channels""": 14,
							    """down_block_types""": ["""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""],
							    """up_block_types""": [],
							    """out_block_type""": """ValueFunction""",
							    """mid_block_type""": """ValueFunctionMidBlock1D""",
							    """block_out_channels""": [32, 64, 128, 256],
							    """layers_per_block""": 1,
							    """downsample_each_block""": True,
							    """use_timestep_embedding""": True,
							    """freq_shift""": 1.0,
							    """flip_sin_to_cos""": False,
							    """time_embedding_type""": """positional""",
							    """act_fn""": """mish""",
							}
							UpperCamelCase__								=						self.dummy_input
							return init_dict, inputs_dict




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	Tuple:
							UpperCamelCase__	,      UpperCamelCase__								=						UNetaDModel.from_pretrained(
							    """bglick13/hopper-medium-v2-value-function-hor32"""     ,   output_loading_info=__lowerCAmelCase     ,   subfolder="""value_function"""							)
							self.assertIsNotNone(__lowerCAmelCase							)
							self.assertEqual(len(vf_loading_info["""missing_keys"""]							)     ,   0							)

							value_function.to(__lowerCAmelCase							)
							UpperCamelCase__								=						value_function(**self.dummy_input							)

							assert image is not None, "Make sure output is not None"




					@unittest.skipIf(torch_device == """mps"""     ,   """mish op not supported in MPS"""							)
					def 						snake_case_		(    self							)    ->	List[Any]:
							UpperCamelCase__	,      UpperCamelCase__								=						UNetaDModel.from_pretrained(
							    """bglick13/hopper-medium-v2-value-function-hor32"""     ,   output_loading_info=__lowerCAmelCase     ,   subfolder="""value_function"""							)
							torch.manual_seed(0							)
							if torch.cuda.is_available():
									torch.cuda.manual_seed_all(0							)

							UpperCamelCase__								=						value_function.config.in_channels
							UpperCamelCase__								=						14
							UpperCamelCase__								=						torch.randn((1, seq_len, num_features)							).permute(
							    0     ,   2     ,   1							)  # match original, we can update values and remove
							UpperCamelCase__								=						torch.full((num_features,)     ,   0							)

							with torch.no_grad():
									UpperCamelCase__								=						value_function(__lowerCAmelCase     ,   __lowerCAmelCase							).sample

							# fmt: off
							UpperCamelCase__								=						torch.tensor([1_6_5.2_5] * seq_len							)
							# fmt: on
							self.assertTrue(torch.allclose(__lowerCAmelCase     ,   __lowerCAmelCase     ,   rtol=1E-3							)							)




					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							# Not implemented yet for this UNet
							pass





