




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


UpperCamelCase								=	logging.get_logger(__name__)


if is_vision_available():
     import PIL





class 					__lowerCamelCase			(       UpperCamelCase__       ):




    """simple docstring"""

    snake_case__   = ["pixel_values"]


    def __init__(			self	:	Optional[int]  ,      SCREAMING_SNAKE_CASE__	:	bool = True  ,      SCREAMING_SNAKE_CASE__	:	Dict[str, int] = None  ,      SCREAMING_SNAKE_CASE__	:	PILImageResampling = PILImageResampling.BICUBIC  ,      SCREAMING_SNAKE_CASE__	:	bool = True  ,      SCREAMING_SNAKE_CASE__	:	Dict[str, int] = None  ,      SCREAMING_SNAKE_CASE__	:	bool = True  ,      SCREAMING_SNAKE_CASE__	:	Union[int, float] = 1 / 255  ,      SCREAMING_SNAKE_CASE__	:	bool = True  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[float, List[float]]] = None  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[float, List[float]]] = None  ,      SCREAMING_SNAKE_CASE__	:	bool = True  ,      **SCREAMING_SNAKE_CASE__	:	Any  ,      ) ->			None:
         super().__init__(**SCREAMING_SNAKE_CASE__  )
         lowerCAmelCase__            =					size if size is not None else {"shortest_edge": 224}
         lowerCAmelCase__            =					get_size_dict(SCREAMING_SNAKE_CASE__  ,      default_to_square=SCREAMING_SNAKE_CASE__  )
         lowerCAmelCase__            =					crop_size if crop_size is not None else {"height": 224, "width": 224}
         lowerCAmelCase__            =					get_size_dict(SCREAMING_SNAKE_CASE__  ,      default_to_square=SCREAMING_SNAKE_CASE__  ,      param_name="crop_size"  )

         lowerCAmelCase__            =					do_resize
         lowerCAmelCase__            =					size
         lowerCAmelCase__            =					resample
         lowerCAmelCase__            =					do_center_crop
         lowerCAmelCase__            =					crop_size
         lowerCAmelCase__            =					do_rescale
         lowerCAmelCase__            =					rescale_factor
         lowerCAmelCase__            =					do_normalize
         lowerCAmelCase__            =					image_mean if image_mean is not None else OPENAI_CLIP_MEAN
         lowerCAmelCase__            =					image_std if image_std is not None else OPENAI_CLIP_STD
         lowerCAmelCase__            =					do_convert_rgb


    def   a (			self	:	Any  ,      SCREAMING_SNAKE_CASE__	:	np.ndarray  ,      SCREAMING_SNAKE_CASE__	:	Dict[str, int]  ,      SCREAMING_SNAKE_CASE__	:	PILImageResampling = PILImageResampling.BICUBIC  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[str, ChannelDimension]] = None  ,      **SCREAMING_SNAKE_CASE__	:	List[Any]  ,      ) ->			np.ndarray:
         lowerCAmelCase__            =					get_size_dict(SCREAMING_SNAKE_CASE__  ,      default_to_square=SCREAMING_SNAKE_CASE__  )
         if "shortest_edge" not in size:
              raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'  )
         lowerCAmelCase__            =					get_resize_output_image_size(SCREAMING_SNAKE_CASE__  ,      size=size["shortest_edge"]  ,      default_to_square=SCREAMING_SNAKE_CASE__  )
         return resize(SCREAMING_SNAKE_CASE__  ,      size=SCREAMING_SNAKE_CASE__  ,      resample=SCREAMING_SNAKE_CASE__  ,      data_format=SCREAMING_SNAKE_CASE__  ,      **SCREAMING_SNAKE_CASE__  )


    def   a (			self	:	Union[str, Any]  ,      SCREAMING_SNAKE_CASE__	:	np.ndarray  ,      SCREAMING_SNAKE_CASE__	:	Dict[str, int]  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[str, ChannelDimension]] = None  ,      **SCREAMING_SNAKE_CASE__	:	Any  ,      ) ->			np.ndarray:
         lowerCAmelCase__            =					get_size_dict(SCREAMING_SNAKE_CASE__  )
         if "height" not in size or "width" not in size:
              raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}'  )
         return center_crop(SCREAMING_SNAKE_CASE__  ,      size=(size["height"], size["width"])  ,      data_format=SCREAMING_SNAKE_CASE__  ,      **SCREAMING_SNAKE_CASE__  )


    def   a (			self	:	Union[str, Any]  ,      SCREAMING_SNAKE_CASE__	:	np.ndarray  ,      SCREAMING_SNAKE_CASE__	:	Union[int, float]  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[str, ChannelDimension]] = None  ,      **SCREAMING_SNAKE_CASE__	:	Dict  ,      ) ->			Optional[Any]:
         return rescale(SCREAMING_SNAKE_CASE__  ,      scale=SCREAMING_SNAKE_CASE__  ,      data_format=SCREAMING_SNAKE_CASE__  ,      **SCREAMING_SNAKE_CASE__  )


    def   a (			self	:	Optional[Any]  ,      SCREAMING_SNAKE_CASE__	:	np.ndarray  ,      SCREAMING_SNAKE_CASE__	:	Union[float, List[float]]  ,      SCREAMING_SNAKE_CASE__	:	Union[float, List[float]]  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[str, ChannelDimension]] = None  ,      **SCREAMING_SNAKE_CASE__	:	int  ,      ) ->			np.ndarray:
         return normalize(SCREAMING_SNAKE_CASE__  ,      mean=SCREAMING_SNAKE_CASE__  ,      std=SCREAMING_SNAKE_CASE__  ,      data_format=SCREAMING_SNAKE_CASE__  ,      **SCREAMING_SNAKE_CASE__  )


    def   a (			self	:	Union[str, Any]  ,      SCREAMING_SNAKE_CASE__	:	ImageInput  ,      SCREAMING_SNAKE_CASE__	:	bool = None  ,      SCREAMING_SNAKE_CASE__	:	Dict[str, int] = None  ,      SCREAMING_SNAKE_CASE__	:	PILImageResampling = None  ,      SCREAMING_SNAKE_CASE__	:	bool = None  ,      SCREAMING_SNAKE_CASE__	:	int = None  ,      SCREAMING_SNAKE_CASE__	:	bool = None  ,      SCREAMING_SNAKE_CASE__	:	float = None  ,      SCREAMING_SNAKE_CASE__	:	bool = None  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[float, List[float]]] = None  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[float, List[float]]] = None  ,      SCREAMING_SNAKE_CASE__	:	bool = None  ,      SCREAMING_SNAKE_CASE__	:	Optional[Union[str, TensorType]] = None  ,      SCREAMING_SNAKE_CASE__	:	Optional[ChannelDimension] = ChannelDimension.FIRST  ,      **SCREAMING_SNAKE_CASE__	:	List[Any]  ,      ) ->			PIL.Image.Image:
         lowerCAmelCase__            =					do_resize if do_resize is not None else self.do_resize
         lowerCAmelCase__            =					size if size is not None else self.size
         lowerCAmelCase__            =					get_size_dict(SCREAMING_SNAKE_CASE__  ,      param_name="size"  ,      default_to_square=SCREAMING_SNAKE_CASE__  )
         lowerCAmelCase__            =					resample if resample is not None else self.resample
         lowerCAmelCase__            =					do_center_crop if do_center_crop is not None else self.do_center_crop
         lowerCAmelCase__            =					crop_size if crop_size is not None else self.crop_size
         lowerCAmelCase__            =					get_size_dict(SCREAMING_SNAKE_CASE__  ,      param_name="crop_size"  ,      default_to_square=SCREAMING_SNAKE_CASE__  )
         lowerCAmelCase__            =					do_rescale if do_rescale is not None else self.do_rescale
         lowerCAmelCase__            =					rescale_factor if rescale_factor is not None else self.rescale_factor
         lowerCAmelCase__            =					do_normalize if do_normalize is not None else self.do_normalize
         lowerCAmelCase__            =					image_mean if image_mean is not None else self.image_mean
         lowerCAmelCase__            =					image_std if image_std is not None else self.image_std
         lowerCAmelCase__            =					do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

         lowerCAmelCase__            =					make_list_of_images(SCREAMING_SNAKE_CASE__  )

         if not valid_images(SCREAMING_SNAKE_CASE__  ):
              raise ValueError(
                  "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
                  "torch.Tensor, tf.Tensor or jax.ndarray."  )

         if do_resize and size is None:
              raise ValueError("Size must be specified if do_resize is True."  )

         if do_center_crop and crop_size is None:
              raise ValueError("Crop size must be specified if do_center_crop is True."  )

         if do_rescale and rescale_factor is None:
              raise ValueError("Rescale factor must be specified if do_rescale is True."  )

         if do_normalize and (image_mean is None or image_std is None):
              raise ValueError("Image mean and std must be specified if do_normalize is True."  )

         # PIL RGBA images are converted to RGB
         if do_convert_rgb:
              lowerCAmelCase__            =					[convert_to_rgb(SCREAMING_SNAKE_CASE__  ) for image in images]

         # All transformations expect numpy arrays.
         lowerCAmelCase__            =					[to_numpy_array(SCREAMING_SNAKE_CASE__  ) for image in images]

         if do_resize:
              lowerCAmelCase__            =					[self.resize(image=SCREAMING_SNAKE_CASE__  ,      size=SCREAMING_SNAKE_CASE__  ,      resample=SCREAMING_SNAKE_CASE__  ) for image in images]

         if do_center_crop:
              lowerCAmelCase__            =					[self.center_crop(image=SCREAMING_SNAKE_CASE__  ,      size=SCREAMING_SNAKE_CASE__  ) for image in images]

         if do_rescale:
              lowerCAmelCase__            =					[self.rescale(image=SCREAMING_SNAKE_CASE__  ,      scale=SCREAMING_SNAKE_CASE__  ) for image in images]

         if do_normalize:
              lowerCAmelCase__            =					[self.normalize(image=SCREAMING_SNAKE_CASE__  ,      mean=SCREAMING_SNAKE_CASE__  ,      std=SCREAMING_SNAKE_CASE__  ) for image in images]

         lowerCAmelCase__            =					[to_channel_dimension_format(SCREAMING_SNAKE_CASE__  ,      SCREAMING_SNAKE_CASE__  ) for image in images]

         lowerCAmelCase__            =					{"pixel_values": images}
         return BatchFeature(data=SCREAMING_SNAKE_CASE__  ,      tensor_type=SCREAMING_SNAKE_CASE__  )




import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation





def 	_lowerCAmelCase					( UpperCamelCase__:  Optional[Any]    )			-> Optional[int]:





	"""simple docstring"""







	A             =					3_84
	if "tiny" in model_name:
		A             =					[3, 3, 9, 3]
		A             =					[96, 1_92, 3_84, 7_68]
	if "small" in model_name:
		A             =					[3, 3, 27, 3]
		A             =					[96, 1_92, 3_84, 7_68]
	if "base" in model_name:
		A             =					[3, 3, 27, 3]
		A             =					[1_28, 2_56, 5_12, 10_24]
		A             =					5_12
	if "large" in model_name:
		A             =					[3, 3, 27, 3]
		A             =					[1_92, 3_84, 7_68, 15_36]
		A             =					7_68
	if "xlarge" in model_name:
		A             =					[3, 3, 27, 3]
		A             =					[2_56, 5_12, 10_24, 20_48]
		A             =					10_24

	# set label information
	A             =					1_50
	A             =					"""huggingface/label-files"""
	A             =					"""ade20k-id2label.json"""
	A             =					json.load(open(hf_hub_download(UpperCamelCase__				,       UpperCamelCase__				,       repo_type="""dataset"""    )				,       """r"""    )    )
	A             =					{int(UpperCamelCase__    ): v for k, v in idalabel.items()}
	A             =					{v: k for k, v in idalabel.items()}

	A             =					ConvNextConfig(
	    depths=UpperCamelCase__				,       hidden_sizes=UpperCamelCase__				,       out_features=["""stage1""", """stage2""", """stage3""", """stage4"""]    )
	A             =					UperNetConfig(
	    backbone_config=UpperCamelCase__				,       auxiliary_in_channels=UpperCamelCase__				,       num_labels=UpperCamelCase__				,       idalabel=UpperCamelCase__				,       labelaid=UpperCamelCase__				,       )

	return config





def 	_lowerCAmelCase					( UpperCamelCase__:  int    )			-> Dict:





	"""simple docstring"""







	A             =					[]

	# fmt: off
	# stem
	rename_keys.append(("""backbone.downsample_layers.0.0.weight""", """backbone.embeddings.patch_embeddings.weight""")    )
	rename_keys.append(("""backbone.downsample_layers.0.0.bias""", """backbone.embeddings.patch_embeddings.bias""")    )
	rename_keys.append(("""backbone.downsample_layers.0.1.weight""", """backbone.embeddings.layernorm.weight""")    )
	rename_keys.append(("""backbone.downsample_layers.0.1.bias""", """backbone.embeddings.layernorm.bias""")    )
	# stages
	for i in range(len(config.backbone_config.depths    )    ):
		for j in range(config.backbone_config.depths[i]    ):
			rename_keys.append((f'backbone.stages.{i}.{j}.gamma', f'backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter')    )
			rename_keys.append((f'backbone.stages.{i}.{j}.depthwise_conv.weight', f'backbone.encoder.stages.{i}.layers.{j}.dwconv.weight')    )
			rename_keys.append((f'backbone.stages.{i}.{j}.depthwise_conv.bias', f'backbone.encoder.stages.{i}.layers.{j}.dwconv.bias')    )
			rename_keys.append((f'backbone.stages.{i}.{j}.norm.weight', f'backbone.encoder.stages.{i}.layers.{j}.layernorm.weight')    )
			rename_keys.append((f'backbone.stages.{i}.{j}.norm.bias', f'backbone.encoder.stages.{i}.layers.{j}.layernorm.bias')    )
			rename_keys.append((f'backbone.stages.{i}.{j}.pointwise_conv1.weight', f'backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight')    )
			rename_keys.append((f'backbone.stages.{i}.{j}.pointwise_conv1.bias', f'backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias')    )
			rename_keys.append((f'backbone.stages.{i}.{j}.pointwise_conv2.weight', f'backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight')    )
			rename_keys.append((f'backbone.stages.{i}.{j}.pointwise_conv2.bias', f'backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias')    )
		if i > 0:
			rename_keys.append((f'backbone.downsample_layers.{i}.0.weight', f'backbone.encoder.stages.{i}.downsampling_layer.0.weight')    )
			rename_keys.append((f'backbone.downsample_layers.{i}.0.bias', f'backbone.encoder.stages.{i}.downsampling_layer.0.bias')    )
			rename_keys.append((f'backbone.downsample_layers.{i}.1.weight', f'backbone.encoder.stages.{i}.downsampling_layer.1.weight')    )
			rename_keys.append((f'backbone.downsample_layers.{i}.1.bias', f'backbone.encoder.stages.{i}.downsampling_layer.1.bias')    )

		rename_keys.append((f'backbone.norm{i}.weight', f'backbone.hidden_states_norms.stage{i+1}.weight')    )
		rename_keys.append((f'backbone.norm{i}.bias', f'backbone.hidden_states_norms.stage{i+1}.bias')    )

	# decode head
	rename_keys.extend(
	    [
	        ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""),
	        ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""),
	        ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""),
	        ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""),
	    ]    )
	# fmt: on

	return rename_keys





def 	_lowerCAmelCase					( UpperCamelCase__:  Tuple				,       UpperCamelCase__:  List[str]				,       UpperCamelCase__:  int    )			-> Optional[Any]:





	"""simple docstring"""







	A             =					dct.pop(UpperCamelCase__    )
	A             =					val





def 	_lowerCAmelCase					( UpperCamelCase__:  Optional[int]				,       UpperCamelCase__:  Any				,       UpperCamelCase__:  int    )			-> List[Any]:





	"""simple docstring"""







	A             =					{
	    """upernet-convnext-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth""",
	    """upernet-convnext-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth""",
	    """upernet-convnext-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth""",
	    """upernet-convnext-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth""",
	    """upernet-convnext-xlarge""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth""",
	}
	A             =					model_name_to_url[model_name]
	A             =					torch.hub.load_state_dict_from_url(UpperCamelCase__				,       map_location="""cpu"""    )["""state_dict"""]

	A             =					get_upernet_config(UpperCamelCase__    )
	A             =					UperNetForSemanticSegmentation(UpperCamelCase__    )
	model.eval()

	# replace "bn" => "batch_norm"
	for key in state_dict.copy().keys():
		A             =					state_dict.pop(UpperCamelCase__    )
		if "bn" in key:
			A             =					key.replace("""bn"""				,       """batch_norm"""    )
		A             =					val

	# rename keys
	A             =					create_rename_keys(UpperCamelCase__    )
	for src, dest in rename_keys:
		rename_key(UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__    )

	model.load_state_dict(UpperCamelCase__    )

	# verify on image
	A             =					"""https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"""
	A             =					Image.open(requests.get(UpperCamelCase__				,       stream=UpperCamelCase__    ).raw    ).convert("""RGB"""    )

	A             =					SegformerImageProcessor()
	A             =					processor(UpperCamelCase__				,       return_tensors="""pt"""    ).pixel_values

	with torch.no_grad():
		A             =					model(UpperCamelCase__    )

	if model_name == "upernet-convnext-tiny":
		A             =					torch.tensor(
		    [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]    )
	elif model_name == "upernet-convnext-small":
		A             =					torch.tensor(
		    [[-8.82_36, -8.82_36, -8.67_71], [-8.82_36, -8.82_36, -8.67_71], [-8.76_38, -8.76_38, -8.62_40]]    )
	elif model_name == "upernet-convnext-base":
		A             =					torch.tensor(
		    [[-8.85_58, -8.85_58, -8.69_05], [-8.85_58, -8.85_58, -8.69_05], [-8.76_69, -8.76_69, -8.60_21]]    )
	elif model_name == "upernet-convnext-large":
		A             =					torch.tensor(
		    [[-8.66_60, -8.66_60, -8.62_10], [-8.66_60, -8.66_60, -8.62_10], [-8.63_10, -8.63_10, -8.59_64]]    )
	elif model_name == "upernet-convnext-xlarge":
		A             =					torch.tensor(
		    [[-8.49_80, -8.49_80, -8.39_77], [-8.49_80, -8.49_80, -8.39_77], [-8.43_79, -8.43_79, -8.34_12]]    )
	print("""Logits:"""				,       outputs.logits[0, 0, :3, :3]    )
	assert torch.allclose(outputs.logits[0, 0, :3, :3]				,       UpperCamelCase__				,       atol=1e-4    )
	print("""Looks ok!"""    )

	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 processor to {pytorch_dump_folder_path}'    )
		processor.save_pretrained(UpperCamelCase__    )

	if push_to_hub:
		print(f'Pushing model and processor for {model_name} to hub'    )
		model.push_to_hub(f'openmmlab/{model_name}'    )
		processor.push_to_hub(f'openmmlab/{model_name}'    )


if __name__ == "__main__":
				_lowercase							:   List[str]						=						argparse.ArgumentParser()
				# Required parameters
				parser.add_argument(
				    "--model_name",
				    default="upernet-convnext-tiny",
				    type=str,
				    choices=[f'''upernet-convnext-{size}''' for size in ["tiny", "small", "base", "large", "xlarge"]],
				    help="Name of the ConvNext UperNet model 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 or not to push the converted model to the 🤗 hub."
				)

				_lowercase							:   str						=						parser.parse_args()
				convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)



