

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 :	Any     				=    get_logger(__name__)







def a_		(       UpperCamelCase_   :							List[Any]  )							->   List[str]:







 """simple docstring"""

 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     lowerCAmelCase				(    __UpperCamelCase				):


       '''simple docstring'''







       snake_case    							=	False  # to tell pytest it's not a test class

       @staticmethod
       def   lowerCamelCase__						(	__snake_case					:  ArgumentParser     )   -> str:







        '''simple docstring'''

        lowerCamelCase      						=    parser.add_parser('test'						,	help='Test dataset implementation.'     )
        test_parser.add_argument('--name'						,	type=__snake_case						,	default=__snake_case						,	help='Dataset processing name'     )
        test_parser.add_argument(
            '--cache_dir'						,	type=__snake_case						,	default=__snake_case						,	help='Cache directory where the datasets are stored.'						,	)
        test_parser.add_argument(
            '--data_dir'						,	type=__snake_case						,	default=__snake_case						,	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=__snake_case						,	help='Name of the dataset to download'     )
        test_parser.set_defaults(func=_test_command_factory     )

       def __init__(	self					:  Tuple						,	__snake_case					:  str						,	__snake_case					:  str						,	__snake_case					:  str						,	__snake_case					:  str						,	__snake_case					:  bool						,	__snake_case					:  bool						,	__snake_case					:  bool						,	__snake_case					:  bool						,	__snake_case					:  bool						,	)   -> Optional[Any]:







        '''simple docstring'''

        lowerCamelCase      						=    dataset
        lowerCamelCase      						=    name
        lowerCamelCase      						=    cache_dir
        lowerCamelCase      						=    data_dir
        lowerCamelCase      						=    all_configs
        lowerCamelCase      						=    save_infos
        lowerCamelCase      						=    ignore_verifications
        lowerCamelCase      						=    force_redownload
        lowerCamelCase      						=    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:
         lowerCamelCase      						=    True





       def   lowerCamelCase__						(	self					:  Union[str, Any]     )   -> List[str]:







        '''simple docstring'''

        fl_logger().setLevel(__snake_case     )
        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     )
        lowerCamelCase						,	lowerCamelCase      						=    self._dataset, self._name
        lowerCamelCase      						=    dataset_module_factory(__snake_case     )
        lowerCamelCase      						=    import_main_class(module.module_path     )
        lowerCamelCase      						=    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=__snake_case						,	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})'''     )
         lowerCamelCase      						=    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=__snake_case						,	)
         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:
          lowerCamelCase      						=    os.path.join(builder_cls.get_imported_module_dir()						,	'README.md'     )
          lowerCamelCase      						=    Path(__snake_case     ).name + '.py'
          lowerCamelCase      						=    os.path.join(__snake_case						,	__snake_case     )
          if os.path.isfile(__snake_case     ):
           lowerCamelCase      						=    os.path.dirname(__snake_case     )
          elif os.path.isfile(__snake_case     ):
           lowerCamelCase      						=    path
          elif os.path.isdir(__snake_case     ):  # for local directories containing only data files
           lowerCamelCase      						=    path
          else:  # in case of a remote dataset
           lowerCamelCase      						=    None
           print(F'''Dataset card saved at {dataset_readme_path}'''     )

          # Move dataset_info back to the user
          if dataset_dir is not None:
           lowerCamelCase      						=    os.path.join(__snake_case						,	'README.md'     )
           copyfile(__snake_case						,	__snake_case     )
           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     )
          lowerCamelCase      						=    os.path.join(self._cache_dir						,	datasets.config.DOWNLOADED_DATASETS_DIR     )
          if os.path.isdir(__snake_case     ):
           logger.warning(F'''Clearing cache at {download_dir}'''     )
           rmtree(__snake_case     )

        print('Test successful.'     )







import inspect
import unittest

from transformers import SwinaSRConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch
     from torch import nn

     from transformers import SwinaSRForImageSuperResolution, SwinaSRModel
     from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
     from PIL import Image

     from transformers import SwinaSRImageProcessor


class     lowerCAmelCase				:


       '''simple docstring'''







       def __init__(	self					:  List[str]						,	__snake_case					:  List[str]						,	__snake_case					:  Dict=13						,	__snake_case					:  Optional[Any]=32						,	__snake_case					:  Union[str, Any]=1						,	__snake_case					:  Dict=3						,	__snake_case					:  List[Any]=16						,	__snake_case					:  Dict=[1, 2, 1]						,	__snake_case					:  Any=[2, 2, 4]						,	__snake_case					:  int=2						,	__snake_case					:  Optional[int]=2.0						,	__snake_case					:  Union[str, Any]=True						,	__snake_case					:  Any=0.0						,	__snake_case					:  Dict=0.0						,	__snake_case					:  List[Any]=0.1						,	__snake_case					:  Tuple="gelu"						,	__snake_case					:  Tuple=False						,	__snake_case					:  Optional[int]=True						,	__snake_case					:  List[str]=0.02						,	__snake_case					:  Tuple=1e-5						,	__snake_case					:  List[str]=True						,	__snake_case					:  Optional[int]=None						,	__snake_case					:  int=False						,	__snake_case					:  Optional[int]=2						,	)   -> Optional[Any]:







        '''simple docstring'''

        lowerCamelCase      						=    parent
        lowerCamelCase      						=    batch_size
        lowerCamelCase      						=    image_size
        lowerCamelCase      						=    patch_size
        lowerCamelCase      						=    num_channels
        lowerCamelCase      						=    embed_dim
        lowerCamelCase      						=    depths
        lowerCamelCase      						=    num_heads
        lowerCamelCase      						=    window_size
        lowerCamelCase      						=    mlp_ratio
        lowerCamelCase      						=    qkv_bias
        lowerCamelCase      						=    hidden_dropout_prob
        lowerCamelCase      						=    attention_probs_dropout_prob
        lowerCamelCase      						=    drop_path_rate
        lowerCamelCase      						=    hidden_act
        lowerCamelCase      						=    use_absolute_embeddings
        lowerCamelCase      						=    patch_norm
        lowerCamelCase      						=    layer_norm_eps
        lowerCamelCase      						=    initializer_range
        lowerCamelCase      						=    is_training
        lowerCamelCase      						=    scope
        lowerCamelCase      						=    use_labels
        lowerCamelCase      						=    upscale

        # here we set some attributes to make tests pass
        lowerCamelCase      						=    len(__snake_case     )
        lowerCamelCase      						=    embed_dim
        lowerCamelCase      						=    (image_size // patch_size) ** 2

       def   lowerCamelCase__						(	self					:  List[Any]     )   -> Optional[Any]:







        '''simple docstring'''

        lowerCamelCase      						=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

        lowerCamelCase      						=    None
        if self.use_labels:
         lowerCamelCase      						=    ids_tensor([self.batch_size]						,	self.type_sequence_label_size     )

        lowerCamelCase      						=    self.get_config()

        return config, pixel_values, labels

       def   lowerCamelCase__						(	self					:  Optional[Any]     )   -> str:







        '''simple docstring'''

        return SwinaSRConfig(
            image_size=self.image_size						,	patch_size=self.patch_size						,	num_channels=self.num_channels						,	embed_dim=self.embed_dim						,	depths=self.depths						,	num_heads=self.num_heads						,	window_size=self.window_size						,	mlp_ratio=self.mlp_ratio						,	qkv_bias=self.qkv_bias						,	hidden_dropout_prob=self.hidden_dropout_prob						,	attention_probs_dropout_prob=self.attention_probs_dropout_prob						,	drop_path_rate=self.drop_path_rate						,	hidden_act=self.hidden_act						,	use_absolute_embeddings=self.use_absolute_embeddings						,	path_norm=self.patch_norm						,	layer_norm_eps=self.layer_norm_eps						,	initializer_range=self.initializer_range						,	upscale=self.upscale						,	)

       def   lowerCamelCase__						(	self					:  List[Any]						,	__snake_case					:  Any						,	__snake_case					:  Union[str, Any]						,	__snake_case					:  Optional[Any]     )   -> str:







        '''simple docstring'''

        lowerCamelCase      						=    SwinaSRModel(config=__snake_case     )
        model.to(__snake_case     )
        model.eval()
        lowerCamelCase      						=    model(__snake_case     )

        self.parent.assertEqual(
            result.last_hidden_state.shape						,	(self.batch_size, self.embed_dim, self.image_size, self.image_size)     )

       def   lowerCamelCase__						(	self					:  Tuple						,	__snake_case					:  str						,	__snake_case					:  Optional[int]						,	__snake_case					:  Dict     )   -> str:







        '''simple docstring'''

        lowerCamelCase      						=    SwinaSRForImageSuperResolution(__snake_case     )
        model.to(__snake_case     )
        model.eval()
        lowerCamelCase      						=    model(__snake_case     )

        lowerCamelCase      						=    self.image_size * self.upscale
        self.parent.assertEqual(
            result.reconstruction.shape						,	(self.batch_size, self.num_channels, expected_image_size, expected_image_size)     )





       def   lowerCamelCase__						(	self					:  str     )   -> Any:







        '''simple docstring'''

        lowerCamelCase      						=    self.prepare_config_and_inputs()
        lowerCamelCase						,	lowerCamelCase						,	lowerCamelCase      						=    config_and_inputs
        lowerCamelCase      						=    {'pixel_values': pixel_values}
        return config, inputs_dict


@require_torch
class     lowerCAmelCase				(    __UpperCamelCase   ,				__UpperCamelCase   ,				unittest.TestCase				):


       '''simple docstring'''







       snake_case    							=	(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
       snake_case    							=	{'feature-extraction': SwinaSRModel} if is_torch_available() else {}

       snake_case    							=	False
       snake_case    							=	False
       snake_case    							=	False
       snake_case    							=	False
       snake_case    							=	False

       def   lowerCamelCase__						(	self					:  Any     )   -> Optional[int]:







        '''simple docstring'''

        lowerCamelCase      						=    SwinaSRModelTester(self     )
        lowerCamelCase      						=    ConfigTester(self						,	config_class=__snake_case						,	embed_dim=37     )

       def   lowerCamelCase__						(	self					:  Optional[Any]     )   -> Dict:







        '''simple docstring'''

        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()

       def   lowerCamelCase__						(	self					:  Optional[int]     )   -> List[Any]:







        '''simple docstring'''

        lowerCamelCase      						=    self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__snake_case     )

       def   lowerCamelCase__						(	self					:  int     )   -> Tuple:







        '''simple docstring'''

        lowerCamelCase      						=    self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_super_resolution(*__snake_case     )

       @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'     )
       def   lowerCamelCase__						(	self					:  List[Any]     )   -> Optional[Any]:







        '''simple docstring'''

        pass

       @unittest.skip(reason='Swin2SR does not use inputs_embeds'     )
       def   lowerCamelCase__						(	self					:  str     )   -> Optional[int]:







        '''simple docstring'''

        pass

       @unittest.skip(reason='Swin2SR does not support training yet'     )
       def   lowerCamelCase__						(	self					:  Dict     )   -> Dict:







        '''simple docstring'''

        pass

       @unittest.skip(reason='Swin2SR does not support training yet'     )
       def   lowerCamelCase__						(	self					:  List[Any]     )   -> int:







        '''simple docstring'''

        pass

       def   lowerCamelCase__						(	self					:  Tuple     )   -> Union[str, Any]:







        '''simple docstring'''

        lowerCamelCase						,	lowerCamelCase      						=    self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         lowerCamelCase      						=    model_class(__snake_case     )
         self.assertIsInstance(model.get_input_embeddings()						,	(nn.Module)     )
         lowerCamelCase      						=    model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(__snake_case						,	nn.Linear     )     )

       def   lowerCamelCase__						(	self					:  List[str]     )   -> Optional[int]:







        '''simple docstring'''

        lowerCamelCase						,	lowerCamelCase      						=    self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         lowerCamelCase      						=    model_class(__snake_case     )
         lowerCamelCase      						=    inspect.signature(model.forward     )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         lowerCamelCase      						=    [*signature.parameters.keys()]

         lowerCamelCase      						=    ['pixel_values']
         self.assertListEqual(arg_names[:1]						,	__snake_case     )

       @slow
       def   lowerCamelCase__						(	self					:  Dict     )   -> List[str]:







        '''simple docstring'''

        for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCamelCase      						=    SwinaSRModel.from_pretrained(__snake_case     )
         self.assertIsNotNone(__snake_case     )

       def   lowerCamelCase__						(	self					:  int     )   -> Union[str, Any]:







        '''simple docstring'''

        lowerCamelCase						,	lowerCamelCase      						=    self.model_tester.prepare_config_and_inputs_for_common()

        lowerCamelCase      						=    _config_zero_init(__snake_case     )
        for model_class in self.all_model_classes:
         lowerCamelCase      						=    model_class(config=__snake_case     )
         for name, param in model.named_parameters():
          if "logit_scale" in name:
           continue
          if param.requires_grad:
           self.assertIn(
               ((param.data.mean() * 1e9).round() / 1e9).item()						,	[0.0, 1.0]						,	msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''						,	)





       def   lowerCamelCase__						(	self					:  int     )   -> Tuple:







        '''simple docstring'''

        lowerCamelCase						,	lowerCamelCase      						=    self.model_tester.prepare_config_and_inputs_for_common()
        lowerCamelCase      						=    True

        for model_class in self.all_model_classes:
         lowerCamelCase      						=    True
         lowerCamelCase      						=    False
         lowerCamelCase      						=    True
         lowerCamelCase      						=    model_class(__snake_case     )
         model.to(__snake_case     )
         model.eval()
         with torch.no_grad():
          lowerCamelCase      						=    model(**self._prepare_for_class(__snake_case						,	__snake_case     )     )
         lowerCamelCase      						=    outputs.attentions
         lowerCamelCase      						=    len(self.model_tester.depths     )
         self.assertEqual(len(__snake_case     )						,	__snake_case     )

         # check that output_attentions also work using config
         del inputs_dict["output_attentions"]
         lowerCamelCase      						=    True
         lowerCamelCase      						=    config.window_size**2
         lowerCamelCase      						=    model_class(__snake_case     )
         model.to(__snake_case     )
         model.eval()
         with torch.no_grad():
          lowerCamelCase      						=    model(**self._prepare_for_class(__snake_case						,	__snake_case     )     )
         lowerCamelCase      						=    outputs.attentions
         self.assertEqual(len(__snake_case     )						,	__snake_case     )

         self.assertListEqual(
             list(attentions[0].shape[-3:]     )						,	[self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,	)
         lowerCamelCase      						=    len(__snake_case     )

         # Check attention is always last and order is fine
         lowerCamelCase      						=    True
         lowerCamelCase      						=    True
         lowerCamelCase      						=    model_class(__snake_case     )
         model.to(__snake_case     )
         model.eval()
         with torch.no_grad():
          lowerCamelCase      						=    model(**self._prepare_for_class(__snake_case						,	__snake_case     )     )

         self.assertEqual(out_len + 1						,	len(__snake_case     )     )

         lowerCamelCase      						=    outputs.attentions

         self.assertEqual(len(__snake_case     )						,	__snake_case     )

         self.assertListEqual(
             list(self_attentions[0].shape[-3:]     )						,	[self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,	)


@require_vision
@require_torch
@slow
class     lowerCAmelCase				(    unittest.TestCase				):


       '''simple docstring'''







       def   lowerCamelCase__						(	self					:  Dict     )   -> Union[str, Any]:







        '''simple docstring'''

        lowerCamelCase      						=    SwinaSRImageProcessor()
        lowerCamelCase      						=    SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64'     ).to(__snake_case     )

        lowerCamelCase      						=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
        lowerCamelCase      						=    processor(images=__snake_case						,	return_tensors='pt'     ).to(__snake_case     )

        # forward pass
        with torch.no_grad():
         lowerCamelCase      						=    model(**__snake_case     )

        # verify the logits
        lowerCamelCase      						=    torch.Size([1, 3, 976, 1296]     )
        self.assertEqual(outputs.reconstruction.shape						,	__snake_case     )
        lowerCamelCase      						=    torch.tensor(
            [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]]     ).to(__snake_case     )
        self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]						,	__snake_case						,	atol=1e-4     )     )




