






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 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__			,     UpperCamelCase__=13			,     UpperCamelCase__=32			,     UpperCamelCase__=1			,     UpperCamelCase__=3			,     UpperCamelCase__=16			,     UpperCamelCase__=[1, 2, 1]			,     UpperCamelCase__=[2, 2, 4]			,     UpperCamelCase__=2			,     UpperCamelCase__=2.0			,     UpperCamelCase__=True			,     UpperCamelCase__=0.0			,     UpperCamelCase__=0.0			,     UpperCamelCase__=0.1			,     UpperCamelCase__="gelu"			,     UpperCamelCase__=False			,     UpperCamelCase__=True			,     UpperCamelCase__=0.02			,     UpperCamelCase__=1E-5			,     UpperCamelCase__=True			,     UpperCamelCase__=None			,     UpperCamelCase__=False			,     UpperCamelCase__=2			,     ):
						SCREAMING_SNAKE_CASE_ :						int    				= parent
						SCREAMING_SNAKE_CASE_ :						Any    				= batch_size
						SCREAMING_SNAKE_CASE_ :						int    				= image_size
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= patch_size
						SCREAMING_SNAKE_CASE_ :						Any    				= num_channels
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= embed_dim
						SCREAMING_SNAKE_CASE_ :						Dict    				= depths
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= num_heads
						SCREAMING_SNAKE_CASE_ :						str    				= window_size
						SCREAMING_SNAKE_CASE_ :						Tuple    				= mlp_ratio
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= qkv_bias
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= hidden_dropout_prob
						SCREAMING_SNAKE_CASE_ :						Dict    				= attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= drop_path_rate
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= hidden_act
						SCREAMING_SNAKE_CASE_ :						List[str]    				= use_absolute_embeddings
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= patch_norm
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= layer_norm_eps
						SCREAMING_SNAKE_CASE_ :						Dict    				= initializer_range
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= is_training
						SCREAMING_SNAKE_CASE_ :						Any    				= scope
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= use_labels
						SCREAMING_SNAKE_CASE_ :						int    				= upscale

						# here we set some attributes to make tests pass
						SCREAMING_SNAKE_CASE_ :						str    				= len(a_							)
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= embed_dim
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= (image_size // patch_size) ** 2


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						int    				= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= None
						if self.use_labels:
										SCREAMING_SNAKE_CASE_ :						List[str]    				= ids_tensor([self.batch_size]			,     self.type_sequence_label_size							)

						SCREAMING_SNAKE_CASE_ :						str    				= self.get_config()

						return config, pixel_values, labels


		def 	__snake_case      (    self							):
						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 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Any    				= SwinaSRModel(config=a_							)
						model.to(a_							)
						model.eval()
						SCREAMING_SNAKE_CASE_ :						Any    				= model(a_							)

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


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= SwinaSRForImageSuperResolution(a_							)
						model.to(a_							)
						model.eval()
						SCREAMING_SNAKE_CASE_ :						str    				= model(a_							)

						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= self.image_size * self.upscale
						self.parent.assertEqual(
						    result.reconstruction.shape			,     (self.batch_size, self.num_channels, expected_image_size, expected_image_size)							)






		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						int    				= self.prepare_config_and_inputs()
						SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						Any    				= config_and_inputs
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= {'pixel_values': pixel_values}
						return config, inputs_dict






@require_torch
class 				__a				(	SCREAMING_SNAKE_CASE__			,						SCREAMING_SNAKE_CASE__			,						unittest.TestCase    ):





		'''simple docstring'''



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

		UpperCAmelCase__   :					Tuple					     =    False
		UpperCAmelCase__   :					str					     =    False
		UpperCAmelCase__   :					int					     =    False
		UpperCAmelCase__   :					List[str]					     =    False
		UpperCAmelCase__   :					Tuple					     =    False


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Tuple    				= SwinaSRModelTester(self							)
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= ConfigTester(self			,     config_class=a_			,     embed_dim=37							)


		def 	__snake_case      (    self							):
						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 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*a_							)


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						List[str]    				= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_super_resolution(*a_							)


		@unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'							)
		def 	__snake_case      (    self							):
						pass


		@unittest.skip(reason='Swin2SR does not use inputs_embeds'							)
		def 	__snake_case      (    self							):
						pass


		@unittest.skip(reason='Swin2SR does not support training yet'							)
		def 	__snake_case      (    self							):
						pass


		@unittest.skip(reason='Swin2SR does not support training yet'							)
		def 	__snake_case      (    self							):
						pass


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						int    				= self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										SCREAMING_SNAKE_CASE_ :						Tuple    				= model_class(a_							)
										self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module)							)
										SCREAMING_SNAKE_CASE_ :						List[str]    				= model.get_output_embeddings()
										self.assertTrue(x is None or isinstance(a_			,     nn.Linear							)							)


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						Dict    				= self.model_tester.prepare_config_and_inputs_for_common()

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

										SCREAMING_SNAKE_CASE_ :						Dict    				= ['pixel_values']
										self.assertListEqual(arg_names[:1]			,     a_							)


		@slow
		def 	__snake_case      (    self							):



						for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										SCREAMING_SNAKE_CASE_ :						List[Any]    				= SwinaSRModel.from_pretrained(a_							)
										self.assertIsNotNone(a_							)


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						Optional[int]    				= self.model_tester.prepare_config_and_inputs_for_common()

						SCREAMING_SNAKE_CASE_ :						List[str]    				= _config_zero_init(a_							)
						for model_class in self.all_model_classes:
										SCREAMING_SNAKE_CASE_ :						List[str]    				= model_class(config=a_							)
										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 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= self.model_tester.prepare_config_and_inputs_for_common()
						SCREAMING_SNAKE_CASE_ :						Tuple    				= True

						for model_class in self.all_model_classes:
										SCREAMING_SNAKE_CASE_ :						int    				= True
										SCREAMING_SNAKE_CASE_ :						Dict    				= False
										SCREAMING_SNAKE_CASE_ :						Dict    				= True
										SCREAMING_SNAKE_CASE_ :						int    				= model_class(a_							)
										model.to(a_							)
										model.eval()
										with torch.no_grad():
														SCREAMING_SNAKE_CASE_ :						Any    				= model(**self._prepare_for_class(a_			,     a_							)							)
										SCREAMING_SNAKE_CASE_ :						Dict    				= outputs.attentions
										SCREAMING_SNAKE_CASE_ :						Optional[int]    				= len(self.model_tester.depths							)
										self.assertEqual(len(a_							)			,     a_							)

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

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

										# Check attention is always last and order is fine
										SCREAMING_SNAKE_CASE_ :						List[str]    				= True
										SCREAMING_SNAKE_CASE_ :						Any    				= True
										SCREAMING_SNAKE_CASE_ :						List[Any]    				= model_class(a_							)
										model.to(a_							)
										model.eval()
										with torch.no_grad():
														SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= model(**self._prepare_for_class(a_			,     a_							)							)

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

										SCREAMING_SNAKE_CASE_ :						List[str]    				= outputs.attentions

										self.assertEqual(len(a_							)			,     a_							)

										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 				__a				(	unittest.TestCase    ):





		'''simple docstring'''



		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= SwinaSRImageProcessor()
						SCREAMING_SNAKE_CASE_ :						List[str]    				= SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64'							).to(a_							)

						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
						SCREAMING_SNAKE_CASE_ :						Tuple    				= processor(images=a_			,     return_tensors='pt'							).to(a_							)

						# forward pass
						with torch.no_grad():
										SCREAMING_SNAKE_CASE_ :						int    				= model(**a_							)

						# verify the logits
						SCREAMING_SNAKE_CASE_ :						Tuple    				= torch.Size([1, 3, 976, 1296]							)
						self.assertEqual(outputs.reconstruction.shape			,     a_							)
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= torch.tensor(
						    [[0.54_58, 0.55_46, 0.56_38], [0.55_26, 0.55_65, 0.56_51], [0.53_96, 0.54_26, 0.56_21]]							).to(a_							)
						self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]			,     a_			,     atol=1E-4							)							)



'''simple docstring'''

import csv
import json
import os

import datasets


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
__lowercase:		Tuple    						=  "\\n@InProceedings{huggingface:dataset,\ntitle = {A great new dataset},\nauthor={huggingface, Inc.\n},\nyear={2020}\n}\n"

# TODO: Add description of the dataset here
# You can copy an official description
__lowercase:		Optional[int]    						=  "\\nThis new dataset is designed to solve this great NLP task and is crafted with a lot of care.\n"

# TODO: Add a link to an official homepage for the dataset here
__lowercase:		List[str]    						=  ""

# TODO: Add the licence for the dataset here if you can find it
__lowercase:		List[Any]    						=  ""

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
__lowercase:		List[str]    						=  {
    "first_domain": "https://huggingface.co/great-new-dataset-first_domain.zip",
    "second_domain": "https://huggingface.co/great-new-dataset-second_domain.zip",
}







class 			UpperCAmelCase			(							datasets.GeneratorBasedBuilder):
 _lowerCamelCase			:       List[str]            =       datasets.Version('1.1.0')

 # This is an example of a dataset with multiple configurations.
 # If you don't want/need to define several sub-sets in your dataset,
 # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

 # If you need to make complex sub-parts in the datasets with configurable options
 # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
 # BUILDER_CONFIG_CLASS = MyBuilderConfig

 # You will be able to load one or the other configurations in the following list with
 # data = datasets.load_dataset('my_dataset', 'first_domain')
 # data = datasets.load_dataset('my_dataset', 'second_domain')
 _lowerCamelCase			:       Dict            =       [
     datasets.BuilderConfig(name='first_domain'		,      version=SCREAMING_SNAKE_CASE__		,      description='This part of my dataset covers a first domain'),
     datasets.BuilderConfig(name='second_domain'		,      version=SCREAMING_SNAKE_CASE__		,      description='This part of my dataset covers a second domain'),
 ]

 _lowerCamelCase			:       Any            =       'first_domain'  # It's not mandatory to have a default configuration. Just use one if it make sense.

 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    if self.config.name == "first_domain":  # This is the name of the configuration selected in BUILDER_CONFIGS above
       UpperCamelCase__			    =    datasets.Features(
           {
               "sentence": datasets.Value("string"       ),
               "option1": datasets.Value("string"       ),
               "answer": datasets.Value("string"       )
               # These are the features of your dataset like images, labels ...
           }       )
    else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
       UpperCamelCase__			    =    datasets.Features(
           {
               "sentence": datasets.Value("string"       ),
               "option2": datasets.Value("string"       ),
               "second_domain_answer": datasets.Value("string"       )
               # These are the features of your dataset like images, labels ...
           }       )
    return datasets.DatasetInfo(
        # This is the description that will appear on the datasets page.
        description=_DESCRIPTION,       features=a_,       homepage=_HOMEPAGE,       license=_LICENSE,       citation=_CITATION,       )

 def 		lowercase_    (			self			:						Any,       a_			:						Union[str, Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    _URLS[self.config.name]
    UpperCamelCase__			    =    dl_manager.download_and_extract(a_       )
    return [
        datasets.SplitGenerator(
            name=datasets.Split.TRAIN,       gen_kwargs={
                "filepath": os.path.join(a_,       "train.jsonl"       ),
                "split": "train",
            },       ),
        datasets.SplitGenerator(
            name=datasets.Split.VALIDATION,       gen_kwargs={
                "filepath": os.path.join(a_,       "dev.jsonl"       ),
                "split": "dev",
            },       ),
        datasets.SplitGenerator(
            name=datasets.Split.TEST,       gen_kwargs={
                "filepath": os.path.join(a_,       "test.jsonl"       ),
                "split": "test"
            },       ),
    ]

 def 		lowercase_    (			self			:						str,       a_			:						Optional[Any],       a_			:						Tuple       ):





    """simple docstring"""



    with open(a_,       encoding="utf-8"       ) as f:
       for key, row in enumerate(a_       ):
          UpperCamelCase__			    =    json.loads(a_       )
          if self.config.name == "first_domain":
             # Yields examples as (key, example) tuples
             yield key, {
                 "sentence": data["sentence"],
                 "option1": data["option1"],
                 "answer": "" if split == "test" else data["answer"],
             }
          else:
             yield key, {
                 "sentence": data["sentence"],
                 "option2": data["option2"],
                 "second_domain_answer": "" if split == "test" else data["second_domain_answer"],
             }