






"""simple docstring"""





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							:    Optional[Any],      UpperCAmelCase__							:    Optional[int],      UpperCAmelCase__							:    Optional[Any]=1_3,      UpperCAmelCase__							:    Dict=3_2,      UpperCAmelCase__							:    Union[str, Any]=1,      UpperCAmelCase__							:    Optional[int]=3,      UpperCAmelCase__							:    Union[str, Any]=1_6,      UpperCAmelCase__							:    List[str]=[1, 2, 1],      UpperCAmelCase__							:    Union[str, Any]=[2, 2, 4],      UpperCAmelCase__							:    Tuple=2,      UpperCAmelCase__							:    int=2.0,      UpperCAmelCase__							:    Union[str, Any]=True,      UpperCAmelCase__							:    List[Any]=0.0,      UpperCAmelCase__							:    Tuple=0.0,      UpperCAmelCase__							:    List[str]=0.1,      UpperCAmelCase__							:    str="gelu",      UpperCAmelCase__							:    str=False,      UpperCAmelCase__							:    int=True,      UpperCAmelCase__							:    Any=0.02,      UpperCAmelCase__							:    Tuple=1E-5,      UpperCAmelCase__							:    Dict=True,      UpperCAmelCase__							:    Tuple=None,      UpperCAmelCase__							:    Dict=False,      UpperCAmelCase__							:    List[Any]=2,      ):
    __lowercase			=		parent
    __lowercase			=		batch_size
    __lowercase			=		image_size
    __lowercase			=		patch_size
    __lowercase			=		num_channels
    __lowercase			=		embed_dim
    __lowercase			=		depths
    __lowercase			=		num_heads
    __lowercase			=		window_size
    __lowercase			=		mlp_ratio
    __lowercase			=		qkv_bias
    __lowercase			=		hidden_dropout_prob
    __lowercase			=		attention_probs_dropout_prob
    __lowercase			=		drop_path_rate
    __lowercase			=		hidden_act
    __lowercase			=		use_absolute_embeddings
    __lowercase			=		patch_norm
    __lowercase			=		layer_norm_eps
    __lowercase			=		initializer_range
    __lowercase			=		is_training
    __lowercase			=		scope
    __lowercase			=		use_labels
    __lowercase			=		upscale

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


 def       _lowercase				(    self							:    Optional[Any]			):
    __lowercase			=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

    __lowercase			=		self.get_config()

    return config, pixel_values, labels


 def       _lowercase				(    self							:    Optional[Any]			):
    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       _lowercase				(    self							:    Optional[Any],      UpperCAmelCase__							:    Union[str, Any],      UpperCAmelCase__							:    Tuple,      UpperCAmelCase__							:    Any			):
    __lowercase			=		SwinaSRModel(config=lowercase_			)
    model.to(lowercase_			)
    model.eval()
    __lowercase			=		model(lowercase_			)

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


 def       _lowercase				(    self							:    Optional[Any],      UpperCAmelCase__							:    List[str],      UpperCAmelCase__							:    int,      UpperCAmelCase__							:    List[Any]			):
    __lowercase			=		SwinaSRForImageSuperResolution(lowercase_			)
    model.to(lowercase_			)
    model.eval()
    __lowercase			=		model(lowercase_			)

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



 def       _lowercase				(    self							:    Any			):
    __lowercase			=		self.prepare_config_and_inputs()
    __lowercase	,__lowercase	,__lowercase			=		config_and_inputs
    __lowercase			=		{"pixel_values": pixel_values}
    return config, inputs_dict







@require_torch
class       _lowerCAmelCase						(			lowerCamelCase__  ,lowerCamelCase__  ,unittest.TestCase     ):







 """simple docstring"""







 __UpperCAmelCase			:      Dict     	=			(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
 __UpperCAmelCase			:      Optional[int]     	=			{'feature-extraction': SwinaSRModel} if is_torch_available() else {}

 __UpperCAmelCase			:      str     	=			False
 __UpperCAmelCase			:      Any     	=			False
 __UpperCAmelCase			:      Dict     	=			False
 __UpperCAmelCase			:      int     	=			False
 __UpperCAmelCase			:      Any     	=			False


 def       _lowercase				(    self							:    List[str]			):
    __lowercase			=		SwinaSRModelTester(self			)
    __lowercase			=		ConfigTester(self,      config_class=lowercase_,      embed_dim=3_7			)


 def       _lowercase				(    self							:    List[Any]			):
    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       _lowercase				(    self							:    List[str]			):
    __lowercase			=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowercase_			)


 def       _lowercase				(    self							:    Tuple			):
    __lowercase			=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_super_resolution(*lowercase_			)


 @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0."			)
 def       _lowercase				(    self							:    Optional[int]			):
    pass


 @unittest.skip(reason="Swin2SR does not use inputs_embeds"			)
 def       _lowercase				(    self							:    Any			):
    pass


 @unittest.skip(reason="Swin2SR does not support training yet"			)
 def       _lowercase				(    self							:    Any			):
    pass


 @unittest.skip(reason="Swin2SR does not support training yet"			)
 def       _lowercase				(    self							:    Any			):
    pass


 def       _lowercase				(    self							:    Optional[Any]			):
    __lowercase	,__lowercase			=		self.model_tester.prepare_config_and_inputs_for_common()

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


 def       _lowercase				(    self							:    Optional[Any]			):
    __lowercase	,__lowercase			=		self.model_tester.prepare_config_and_inputs_for_common()

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

       __lowercase			=		["pixel_values"]
       self.assertListEqual(arg_names[:1],      lowercase_			)


 @slow
 def       _lowercase				(    self							:    Union[str, Any]			):






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


 def       _lowercase				(    self							:    List[str]			):
    __lowercase	,__lowercase			=		self.model_tester.prepare_config_and_inputs_for_common()

    __lowercase			=		_config_zero_init(lowercase_			)
    for model_class in self.all_model_classes:
       __lowercase			=		model_class(config=lowercase_			)
       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       _lowercase				(    self							:    Any			):
    __lowercase	,__lowercase			=		self.model_tester.prepare_config_and_inputs_for_common()
    __lowercase			=		True

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

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

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

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

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

       __lowercase			=		outputs.attentions

       self.assertEqual(len(lowercase_			),      lowercase_			)

       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       _lowercase				(    self							:    Tuple			):
    __lowercase			=		SwinaSRImageProcessor()
    __lowercase			=		SwinaSRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x2-64"			).to(lowercase_			)

    __lowercase			=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
    __lowercase			=		processor(images=lowercase_,      return_tensors="pt"			).to(lowercase_			)

    # forward pass
    with torch.no_grad():
       __lowercase			=		model(**lowercase_			)

    # verify the logits
    __lowercase			=		torch.Size([1, 3, 9_7_6, 1_2_9_6]			)
    self.assertEqual(outputs.reconstruction.shape,      lowercase_			)
    __lowercase			=		torch.tensor(
        [[0.5_458, 0.5_546, 0.5_638], [0.5_526, 0.5_565, 0.5_651], [0.5_396, 0.5_426, 0.5_621]]			).to(lowercase_			)
    self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3],      lowercase_,      atol=1E-4			)			)







"""simple docstring"""





import textwrap

import pyarrow as pa
import pytest

from datasets import Features, Value
from datasets.packaged_modules.json.json import Json




@pytest.fixture
def 						_A						(						UpperCamelCase_  : str)			->		Tuple:
   '''simple docstring'''


   __lowercase			=		tmp_path / "file.jsonl"
   __lowercase			=		textwrap.dedent(
       "\\n        {\"col_1\": -1}\n        {\"col_1\": 1, \"col_2\": 2}\n        {\"col_1\": 10, \"col_2\": 20}\n        ")
   with open(UpperCamelCase_,    "w") as f:
      f.write(UpperCamelCase_)
   return str(UpperCamelCase_)




@pytest.fixture
def 						_A						(						UpperCamelCase_  : str)			->		Any:
   '''simple docstring'''


   __lowercase			=		tmp_path / "file_utf16_encoded.jsonl"
   __lowercase			=		textwrap.dedent(
       "\\n        {\"col_1\": -1}\n        {\"col_1\": 1, \"col_2\": 2}\n        {\"col_1\": 10, \"col_2\": 20}\n        ")
   with open(UpperCamelCase_,    "w",    encoding="utf-16") as f:
      f.write(UpperCamelCase_)
   return str(UpperCamelCase_)




@pytest.fixture
def 						_A						(						UpperCamelCase_  : Optional[int])			->		Optional[Any]:
   '''simple docstring'''


   __lowercase			=		tmp_path / "file_with_list_of_dicts.json"
   __lowercase			=		textwrap.dedent(
       "\\n        [\n            {\"col_1\": -1},\n            {\"col_1\": 1, \"col_2\": 2},\n            {\"col_1\": 10, \"col_2\": 20}\n        ]\n        ")
   with open(UpperCamelCase_,    "w") as f:
      f.write(UpperCamelCase_)
   return str(UpperCamelCase_)




@pytest.fixture
def 						_A						(						UpperCamelCase_  : str)			->		int:
   '''simple docstring'''


   __lowercase			=		tmp_path / "file_with_list_of_dicts_field.json"
   __lowercase			=		textwrap.dedent(
       "\\n        {\n            \"field1\": 1,\n            \"field2\": \"aabb\",\n            \"field3\": [\n                {\"col_1\": -1},\n                {\"col_1\": 1, \"col_2\": 2},\n                {\"col_1\": 10, \"col_2\": 20}\n            ]\n        }\n        ")
   with open(UpperCamelCase_,    "w") as f:
      f.write(UpperCamelCase_)
   return str(UpperCamelCase_)




@pytest.mark.parametrize(
    "file_fixture, config_kwargs",    [
        ("jsonl_file", {}),
        ("jsonl_file_utf16_encoded", {"encoding": "utf-16"}),
        ("json_file_with_list_of_dicts", {}),
        ("json_file_with_list_of_dicts_field", {"field": "field3"}),
    ],    )
def 						_A						(						UpperCamelCase_  : Any,    UpperCamelCase_  : List[Any],    UpperCamelCase_  : Optional[Any])			->		List[Any]:
   '''simple docstring'''


   __lowercase			=		Json(**UpperCamelCase_)
   __lowercase			=		json._generate_tables([[request.getfixturevalue(UpperCamelCase_)]])
   __lowercase			=		pa.concat_tables([table for _, table in generator])
   assert pa_table.to_pydict() == {"col_1": [-1, 1, 10], "col_2": [None, 2, 20]}




@pytest.mark.parametrize(
    "file_fixture, config_kwargs",    [
        (
            "jsonl_file",
            {"features": Features({"col_1": Value("int64"), "col_2": Value("int64"), "missing_col": Value("string")})},
        ),
        (
            "json_file_with_list_of_dicts",
            {"features": Features({"col_1": Value("int64"), "col_2": Value("int64"), "missing_col": Value("string")})},
        ),
        (
            "json_file_with_list_of_dicts_field",
            {
                "field": "field3",
                "features": Features(
                    {"col_1": Value("int64"), "col_2": Value("int64"), "missing_col": Value("string")}),
            },
        ),
    ],    )
def 						_A						(						UpperCamelCase_  : Optional[int],    UpperCamelCase_  : int,    UpperCamelCase_  : str)			->		Optional[int]:
   '''simple docstring'''


   __lowercase			=		Json(**UpperCamelCase_)
   __lowercase			=		json._generate_tables([[request.getfixturevalue(UpperCamelCase_)]])
   __lowercase			=		pa.concat_tables([table for _, table in generator])
   assert pa_table.to_pydict() == {"col_1": [-1, 1, 10], "col_2": [None, 2, 20], "missing_col": [None, None, None]}




