


"""simple docstring"""


import argparse

import requests
import torch
from PIL import Image
from torchvision.transforms import Compose, Normalize, Resize, ToTensor

from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor


def _lowerCamelCase	(		_UpperCamelCase      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			SwinaSRConfig()

			if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url:
						__lowerCAmelCase				    =			4
			elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url:
						__lowerCAmelCase				    =			4
						__lowerCAmelCase				    =			48
						__lowerCAmelCase				    =			"pixelshuffle_aux"
			elif "Swin2SR_Lightweight_X2_64" in checkpoint_url:
						__lowerCAmelCase				    =			[6, 6, 6, 6]
						__lowerCAmelCase				    =			60
						__lowerCAmelCase				    =			[6, 6, 6, 6]
						__lowerCAmelCase				    =			"pixelshuffledirect"
			elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url:
						__lowerCAmelCase				    =			4
						__lowerCAmelCase				    =			"nearest+conv"
			elif "Swin2SR_Jpeg_dynamic" in checkpoint_url:
						__lowerCAmelCase				    =			1
						__lowerCAmelCase				    =			1
						__lowerCAmelCase				    =			126
						__lowerCAmelCase				    =			7
						__lowerCAmelCase				    =			2_55.0
						__lowerCAmelCase				    =			""

			return config


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase      ):

			'''simple docstring'''




			if "patch_embed.proj" in name and "layers" not in name:
						__lowerCAmelCase				    =			name.replace("patch_embed.proj"    , "embeddings.patch_embeddings.projection"      )
			if "patch_embed.norm" in name:
						__lowerCAmelCase				    =			name.replace("patch_embed.norm"    , "embeddings.patch_embeddings.layernorm"      )
			if "layers" in name:
						__lowerCAmelCase				    =			name.replace("layers"    , "encoder.stages"      )
			if "residual_group.blocks" in name:
						__lowerCAmelCase				    =			name.replace("residual_group.blocks"    , "layers"      )
			if "attn.proj" in name:
						__lowerCAmelCase				    =			name.replace("attn.proj"    , "attention.output.dense"      )
			if "attn" in name:
						__lowerCAmelCase				    =			name.replace("attn"    , "attention.self"      )
			if "norm1" in name:
						__lowerCAmelCase				    =			name.replace("norm1"    , "layernorm_before"      )
			if "norm2" in name:
						__lowerCAmelCase				    =			name.replace("norm2"    , "layernorm_after"      )
			if "mlp.fc1" in name:
						__lowerCAmelCase				    =			name.replace("mlp.fc1"    , "intermediate.dense"      )
			if "mlp.fc2" in name:
						__lowerCAmelCase				    =			name.replace("mlp.fc2"    , "output.dense"      )
			if "q_bias" in name:
						__lowerCAmelCase				    =			name.replace("q_bias"    , "query.bias"      )
			if "k_bias" in name:
						__lowerCAmelCase				    =			name.replace("k_bias"    , "key.bias"      )
			if "v_bias" in name:
						__lowerCAmelCase				    =			name.replace("v_bias"    , "value.bias"      )
			if "cpb_mlp" in name:
						__lowerCAmelCase				    =			name.replace("cpb_mlp"    , "continuous_position_bias_mlp"      )
			if "patch_embed.proj" in name:
						__lowerCAmelCase				    =			name.replace("patch_embed.proj"    , "patch_embed.projection"      )

			if name == "norm.weight":
						__lowerCAmelCase				    =			"layernorm.weight"
			if name == "norm.bias":
						__lowerCAmelCase				    =			"layernorm.bias"

			if "conv_first" in name:
						__lowerCAmelCase				    =			name.replace("conv_first"    , "first_convolution"      )

			if (
			    "upsample" in name
			    or "conv_before_upsample" in name
			    or "conv_bicubic" in name
			    or "conv_up" in name
			    or "conv_hr" in name
			    or "conv_last" in name
			    or "aux" in name
			):
						# heads
						if "conv_last" in name:
									__lowerCAmelCase				    =			name.replace("conv_last"    , "final_convolution"      )
						if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]:
									if "conv_before_upsample.0" in name:
												__lowerCAmelCase				    =			name.replace("conv_before_upsample.0"    , "conv_before_upsample"      )
									if "upsample.0" in name:
												__lowerCAmelCase				    =			name.replace("upsample.0"    , "upsample.convolution_0"      )
									if "upsample.2" in name:
												__lowerCAmelCase				    =			name.replace("upsample.2"    , "upsample.convolution_1"      )
									__lowerCAmelCase				    =			"upsample." + name
						elif config.upsampler == "pixelshuffledirect":
									__lowerCAmelCase				    =			name.replace("upsample.0.weight"    , "upsample.conv.weight"      )
									__lowerCAmelCase				    =			name.replace("upsample.0.bias"    , "upsample.conv.bias"      )
						else:
									pass
			else:
						__lowerCAmelCase				    =			"swin2sr." + name

			return name


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase      ):

			'''simple docstring'''




			for key in orig_state_dict.copy().keys():
						__lowerCAmelCase				    =			orig_state_dict.pop(_UpperCamelCase      )

						if "qkv" in key:
									__lowerCAmelCase				    =			key.split("."      )
									__lowerCAmelCase				    =			int(key_split[1]      )
									__lowerCAmelCase				    =			int(key_split[4]      )
									__lowerCAmelCase				    =			config.embed_dim

									if "weight" in key:
												__lowerCAmelCase				    =			val[:dim, :]
												__lowerCAmelCase				    =			val[dim : dim * 2, :]
												__lowerCAmelCase				    =			val[-dim:, :]
									else:
												__lowerCAmelCase				    =			val[:dim]
												__lowerCAmelCase				    =			val[dim : dim * 2]
												__lowerCAmelCase				    =			val[-dim:]
									pass
						else:
									__lowerCAmelCase				    =			val

			return orig_state_dict


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			get_config(_UpperCamelCase      )
			__lowerCAmelCase				    =			SwinaSRForImageSuperResolution(_UpperCamelCase      )
			model.eval()

			__lowerCAmelCase				    =			torch.hub.load_state_dict_from_url(_UpperCamelCase    , map_location="cpu"      )
			__lowerCAmelCase				    =			convert_state_dict(_UpperCamelCase    , _UpperCamelCase      )
			__lowerCAmelCase    ,	__lowerCAmelCase				    =			model.load_state_dict(_UpperCamelCase    , strict=_UpperCamelCase      )

			if len(_UpperCamelCase      ) > 0:
						raise ValueError("Missing keys when converting: {}".format(_UpperCamelCase      )      )
			for key in unexpected_keys:
						if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key):
									raise ValueError(f"Unexpected key {key} in state_dict"      )

    # verify values
			__lowerCAmelCase				    =			"https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true"
			__lowerCAmelCase				    =			Image.open(requests.get(_UpperCamelCase    , stream=_UpperCamelCase      ).raw      ).convert("RGB"      )
			__lowerCAmelCase				    =			SwinaSRImageProcessor()
			# pixel_values = processor(image, return_tensors="pt").pixel_values

			__lowerCAmelCase				    =			126 if "Jpeg" in checkpoint_url else 256
			__lowerCAmelCase				    =			Compose(
			    [
			        Resize((image_size, image_size)      ),
			        ToTensor(),
			        Normalize(mean=[0.4_85, 0.4_56, 0.4_06]    , std=[0.2_29, 0.2_24, 0.2_25]      ),
			    ]      )
			__lowerCAmelCase				    =			transforms(_UpperCamelCase      ).unsqueeze(0      )

			if config.num_channels == 1:
						__lowerCAmelCase				    =			pixel_values[:, 0, :, :].unsqueeze(1      )

			__lowerCAmelCase				    =			model(_UpperCamelCase      )

			# assert values
			if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url:
						__lowerCAmelCase				    =			torch.Size([1, 3, 512, 512]      )
						__lowerCAmelCase				    =			torch.tensor(
						    [[-0.70_87, -0.71_38, -0.67_21], [-0.83_40, -0.80_95, -0.72_98], [-0.91_49, -0.84_14, -0.79_40]]      )
			elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url:
						__lowerCAmelCase				    =			torch.Size([1, 3, 1024, 1024]      )
						__lowerCAmelCase				    =			torch.tensor(
						    [[-0.77_75, -0.81_05, -0.89_33], [-0.77_64, -0.83_56, -0.92_25], [-0.79_76, -0.86_86, -0.95_79]]      )
			elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url:
						# TODO values didn't match exactly here
						__lowerCAmelCase				    =			torch.Size([1, 3, 1024, 1024]      )
						__lowerCAmelCase				    =			torch.tensor(
						    [[-0.80_35, -0.75_04, -0.74_91], [-0.85_38, -0.81_24, -0.77_82], [-0.88_04, -0.86_51, -0.84_93]]      )
			elif "Swin2SR_Lightweight_X2_64" in checkpoint_url:
						__lowerCAmelCase				    =			torch.Size([1, 3, 512, 512]      )
						__lowerCAmelCase				    =			torch.tensor(
						    [[-0.76_69, -0.86_62, -0.87_67], [-0.88_10, -0.99_62, -0.98_20], [-0.93_40, -1.03_22, -1.11_49]]      )
			elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url:
						__lowerCAmelCase				    =			torch.Size([1, 3, 1024, 1024]      )
						__lowerCAmelCase				    =			torch.tensor(
						    [[-0.52_38, -0.55_57, -0.63_21], [-0.60_16, -0.59_03, -0.63_91], [-0.62_44, -0.63_34, -0.68_89]]      )

			assert (
			    outputs.reconstruction.shape == expected_shape
			), f"Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}"
			assert torch.allclose(outputs.reconstruction[0, 0, :3, :3]    , _UpperCamelCase    , atol=1e-3      )
			print("Looks ok!"      )

			__lowerCAmelCase				    =			{
			    "https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth": (
			        "swin2SR-classical-sr-x2-64"
			    ),
			    "https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth": (
			        "swin2SR-classical-sr-x4-64"
			    ),
			    "https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth": (
			        "swin2SR-compressed-sr-x4-48"
			    ),
			    "https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth": (
			        "swin2SR-lightweight-x2-64"
			    ),
			    "https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth": (
			        "swin2SR-realworld-sr-x4-64-bsrgan-psnr"
			    ),
			}
			__lowerCAmelCase				    =			url_to_name[checkpoint_url]

			if pytorch_dump_folder_path is not None:
						print(f"Saving model {model_name} to {pytorch_dump_folder_path}"      )
						model.save_pretrained(_UpperCamelCase      )
						print(f"Saving image processor to {pytorch_dump_folder_path}"      )
						processor.save_pretrained(_UpperCamelCase      )

			if push_to_hub:
						model.push_to_hub(f"caidas/{model_name}"      )
						processor.push_to_hub(f"caidas/{model_name}"      )


if __name__ == "__main__":
	A     :   Union[str, Any]			    =			argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    "--checkpoint_url",
	    default="https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth",
	    type=str,
	    help="URL of the original Swin2SR checkpoint you'd like to convert.",
	)
	parser.add_argument(
	    "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
	)
	parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the converted model to the hub.")

	A     :   int			    =			parser.parse_args()
	convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)








"""simple docstring"""


import argparse
import os
import re

import packaging.version


A     :   Any			    =			"examples/"
A     :   Optional[Any]			    =			{
    "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"),
    "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"),
    "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","),
    "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"),
}
A     :   Optional[int]			    =			{
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
A     :   List[Any]			    =			"README.md"


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase      ):

			'''simple docstring'''




			with open(_UpperCamelCase    , "r"    , encoding="utf-8"    , newline="\n"      ) as f:
						__lowerCAmelCase				    =			f.read()
			__lowerCAmelCase    ,	__lowerCAmelCase				    =			REPLACE_PATTERNS[pattern]
			__lowerCAmelCase				    =			replace.replace("VERSION"    , _UpperCamelCase      )
			__lowerCAmelCase				    =			re_pattern.sub(_UpperCamelCase    , _UpperCamelCase      )
			with open(_UpperCamelCase    , "w"    , encoding="utf-8"    , newline="\n"      ) as f:
						f.write(_UpperCamelCase      )


def _lowerCamelCase	(		_UpperCamelCase      ):

			'''simple docstring'''




			for folder, directories, fnames in os.walk(_UpperCamelCase      ):
						# Removing some of the folders with non-actively maintained examples from the walk
						if "research_projects" in directories:
									directories.remove("research_projects"      )
						if "legacy" in directories:
									directories.remove("legacy"      )
						for fname in fnames:
									if fname.endswith(".py"      ):
												update_version_in_file(os.path.join(_UpperCamelCase    , _UpperCamelCase      )    , _UpperCamelCase    , pattern="examples"      )


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase=False      ):

			'''simple docstring'''




			for pattern, fname in REPLACE_FILES.items():
						update_version_in_file(_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase      )
			if not patch:
						update_version_in_examples(_UpperCamelCase      )


def _lowerCamelCase	(		):

			'''simple docstring'''




			__lowerCAmelCase				    =			"🤗 Transformers currently provides the following architectures"
			__lowerCAmelCase				    =			"1. Want to contribute a new model?"
			with open(_UpperCamelCase    , "r"    , encoding="utf-8"    , newline="\n"      ) as f:
						__lowerCAmelCase				    =			f.readlines()

			# Find the start of the list.
			__lowerCAmelCase				    =			0
			while not lines[start_index].startswith(_start_prompt      ):
						start_index += 1
			start_index += 1

			__lowerCAmelCase				    =			start_index
			# Update the lines in the model list.
			while not lines[index].startswith(_end_prompt      ):
						if lines[index].startswith("1."      ):
									__lowerCAmelCase				    =			lines[index].replace(
									    "https://huggingface.co/docs/transformers/main/model_doc"    , "https://huggingface.co/docs/transformers/model_doc"    , )
						index += 1

			with open(_UpperCamelCase    , "w"    , encoding="utf-8"    , newline="\n"      ) as f:
						f.writelines(_UpperCamelCase      )


def _lowerCamelCase	(		):

			'''simple docstring'''




			with open(REPLACE_FILES["init"]    , "r"      ) as f:
						__lowerCAmelCase				    =			f.read()
			__lowerCAmelCase				    =			REPLACE_PATTERNS["init"][0].search(_UpperCamelCase      ).groups()[0]
			return packaging.version.parse(_UpperCamelCase      )


def _lowerCamelCase	(		_UpperCamelCase=False      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			get_version()
			if patch and default_version.is_devrelease:
						raise ValueError("Can't create a patch version from the dev branch, checkout a released version!"      )
			if default_version.is_devrelease:
						__lowerCAmelCase				    =			default_version.base_version
			elif patch:
						__lowerCAmelCase				    =			f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
			else:
						__lowerCAmelCase				    =			f"{default_version.major}.{default_version.minor + 1}.0"

			# Now let's ask nicely if that's the right one.
			__lowerCAmelCase				    =			input(f"Which version are you releasing? [{default_version}]"      )
			if len(_UpperCamelCase      ) == 0:
						__lowerCAmelCase				    =			default_version

			print(f"Updating version to {version}."      )
			global_version_update(_UpperCamelCase    , patch=_UpperCamelCase      )
			if not patch:
						print("Cleaning main README, don't forget to run `make fix-copies`."      )
						clean_main_ref_in_model_list()


def _lowerCamelCase	(		):

			'''simple docstring'''




			__lowerCAmelCase				    =			get_version()
			__lowerCAmelCase				    =			f"{current_version.major}.{current_version.minor + 1}.0.dev0"
			__lowerCAmelCase				    =			current_version.base_version

			# Check with the user we got that right.
			__lowerCAmelCase				    =			input(f"Which version are we developing now? [{dev_version}]"      )
			if len(_UpperCamelCase      ) == 0:
						__lowerCAmelCase				    =			dev_version

			print(f"Updating version to {version}."      )
			global_version_update(_UpperCamelCase      )
			print("Cleaning main README, don't forget to run `make fix-copies`."      )
			clean_main_ref_in_model_list()


if __name__ == "__main__":
	A     :   Union[str, Any]			    =			argparse.ArgumentParser()
	parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
	parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
	A     :   Dict			    =			parser.parse_args()
	if not args.post_release:
		pre_release_work(patch=args.patch)
	elif args.patch:
		print("Nothing to do after a patch :-)")
	else:
		post_release_work()




