'''simple docstring'''

import argparse
import json

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

from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
def 			__UpperCamelCase       (   UpperCAmelCase     ):
 lowercase__				:    Tuple  =					[2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2]
 lowercase__				:    Dict  =					True if '''large''' in model_name or '''huge''' in model_name else False
 lowercase__				:    Optional[int]  =					True if '''large''' in model_name or '''huge''' in model_name else False
 lowercase__				:    Optional[int]  =					True if '''large''' in model_name or '''huge''' in model_name else False

 if "large" in model_name or "xlarge" in model_name or "huge" in model_name:
  if "fl3" in model_name:
   lowercase__				:    Tuple  =					[3, 3, 3, 3]
   lowercase__				:    Dict  =					[5, 5, 5, 5]
  elif "fl4" in model_name:
   lowercase__				:    Any  =					[4, 4, 4, 4]
   lowercase__				:    List[str]  =					[3, 3, 3, 3]

 if "tiny" in model_name or "small" in model_name or "base" in model_name:
  lowercase__				:    Optional[int]  =					[3, 3, 3, 3]
  if "lrf" in model_name:
   lowercase__				:    Any  =					[3, 3, 3, 3]
  else:
   lowercase__				:    int  =					[2, 2, 2, 2]

 if "tiny" in model_name:
  lowercase__				:    str  =					96
 elif "small" in model_name:
  lowercase__				:    Optional[int]  =					96
 elif "base" in model_name:
  lowercase__				:    Any  =					128
 elif "large" in model_name:
  lowercase__				:    Optional[Any]  =					192
 elif "xlarge" in model_name:
  lowercase__				:    List[Any]  =					256
 elif "huge" in model_name:
  lowercase__				:    Union[str, Any]  =					352

 # set label information
 lowercase__				:    Union[str, Any]  =					'''huggingface/label-files'''
 if "large" in model_name or "huge" in model_name:
  lowercase__				:    int  =					'''imagenet-22k-id2label.json'''
 else:
  lowercase__				:    Optional[Any]  =					'''imagenet-1k-id2label.json'''

 lowercase__				:    int  =					json.load(open(hf_hub_download(_snake_case		,     _snake_case		,     repo_type='''dataset'''     )		,     '''r'''     )     )
 lowercase__				:    Dict  =					{int(_snake_case     ): v for k, v in idalabel.items()}
 lowercase__				:    Optional[int]  =					{v: k for k, v in idalabel.items()}

 lowercase__				:    Optional[Any]  =					FocalNetConfig(
     embed_dim=_snake_case		,     depths=_snake_case		,     focal_levels=_snake_case		,     focal_windows=_snake_case		,     use_conv_embed=_snake_case		,     idalabel=_snake_case		,     labelaid=_snake_case		,     use_post_layernorm=_snake_case		,     use_layerscale=_snake_case		,     )

 return config
def 			__UpperCamelCase       (   UpperCAmelCase     ):





 if "patch_embed.proj" in name:
  lowercase__				:    Tuple  =					name.replace('''patch_embed.proj'''		,     '''embeddings.patch_embeddings.projection'''     )
 if "patch_embed.norm" in name:
  lowercase__				:    Tuple  =					name.replace('''patch_embed.norm'''		,     '''embeddings.norm'''     )
 if "layers" in name:
  lowercase__				:    List[Any]  =					'''encoder.''' + name
 if "encoder.layers" in name:
  lowercase__				:    Optional[Any]  =					name.replace('''encoder.layers'''		,     '''encoder.stages'''     )
 if "downsample.proj" in name:
  lowercase__				:    Any  =					name.replace('''downsample.proj'''		,     '''downsample.projection'''     )
 if "blocks" in name:
  lowercase__				:    List[str]  =					name.replace('''blocks'''		,     '''layers'''     )
 if "modulation.f.weight" in name or "modulation.f.bias" in name:
  lowercase__				:    Any  =					name.replace('''modulation.f'''		,     '''modulation.projection_in'''     )
 if "modulation.h.weight" in name or "modulation.h.bias" in name:
  lowercase__				:    List[Any]  =					name.replace('''modulation.h'''		,     '''modulation.projection_context'''     )
 if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
  lowercase__				:    int  =					name.replace('''modulation.proj'''		,     '''modulation.projection_out'''     )

 if name == "norm.weight":
  lowercase__				:    Optional[Any]  =					'''layernorm.weight'''
 if name == "norm.bias":
  lowercase__				:    List[str]  =					'''layernorm.bias'''

 if "head" in name:
  lowercase__				:    Union[str, Any]  =					name.replace('''head'''		,     '''classifier'''     )
 else:
  lowercase__				:    int  =					'''focalnet.''' + name

 return name
def 			__UpperCamelCase       (   UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase=False     ):
 lowercase__				:    List[Any]  =					{
     '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''',
     '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''',
     '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''',
     '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''',
     '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''',
     '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''',
     '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''',
     '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''',
     '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''',
     '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''',
 }
 # fmt: on

 lowercase__				:    int  =					model_name_to_url[model_name]
 print('''Checkpoint URL: '''		,     _snake_case     )
 lowercase__				:    int  =					torch.hub.load_state_dict_from_url(_snake_case		,     map_location='''cpu'''     )['''model''']

 # rename keys
 for key in state_dict.copy().keys():
  lowercase__				:    str  =					state_dict.pop(_snake_case     )
  lowercase__				:    Tuple  =					val

 lowercase__				:    Any  =					get_focalnet_config(_snake_case     )
 lowercase__				:    List[Any]  =					FocalNetForImageClassification(_snake_case     )
 model.eval()

 # load state dict
 model.load_state_dict(_snake_case     )

 # verify conversion
 lowercase__				:    str  =					'''http://images.cocodataset.org/val2017/000000039769.jpg'''

 lowercase__				:    Any  =					BitImageProcessor(
     do_resize=_snake_case		,     size={'''shortest_edge''': 256}		,     resample=PILImageResampling.BILINEAR		,     do_center_crop=_snake_case		,     crop_size=224		,     do_normalize=_snake_case		,     image_mean=_snake_case		,     image_std=_snake_case		,     )
 lowercase__				:    List[str]  =					Image.open(requests.get(_snake_case		,     stream=_snake_case     ).raw     )
 lowercase__				:    int  =					processor(images=_snake_case		,     return_tensors='''pt'''     )

 lowercase__				:    Optional[int]  =					transforms.Compose(
     [
         transforms.Resize(256     ),
         transforms.CenterCrop(224     ),
         transforms.ToTensor(),
         transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6]		,     std=[0.2_2_9, 0.2_2_4, 0.2_2_5]     ),
     ]     )

 lowercase__				:    Optional[Any]  =					image_transforms(_snake_case     ).unsqueeze(0     )

 # verify pixel_values
 assert torch.allclose(inputs.pixel_values		,     _snake_case		,     atol=1E-4     )

 lowercase__				:    Tuple  =					model(**_snake_case     )

 lowercase__				:    str  =					outputs.logits.argmax(-1     ).item()
 print('''Predicted class:'''		,     model.config.idalabel[predicted_class_idx]     )

 print('''First values of logits:'''		,     outputs.logits[0, :3]     )

 if model_name == "focalnet-tiny":
  lowercase__				:    Any  =					torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1]     )
 elif model_name == "focalnet-tiny-lrf":
  lowercase__				:    int  =					torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5]     )
 elif model_name == "focalnet-small":
  lowercase__				:    Optional[int]  =					torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1]     )
 elif model_name == "focalnet-small-lrf":
  lowercase__				:    List[Any]  =					torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1]     )
 elif model_name == "focalnet-base":
  lowercase__				:    Union[str, Any]  =					torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0]     )
 elif model_name == "focalnet-base-lrf":
  lowercase__				:    List[str]  =					torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8]     )
 assert torch.allclose(outputs.logits[0, :3]		,     _snake_case		,     atol=1E-4     )
 print('''Looks ok!'''     )

 if pytorch_dump_folder_path is not None:
  print(F"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}"""     )
  model.save_pretrained(_snake_case     )
  processor.save_pretrained(_snake_case     )

 if push_to_hub:
  print(F"""Pushing model and processor of {model_name} to the hub..."""     )
  model.push_to_hub(F"""{model_name}"""     )
  processor.push_to_hub(F"""{model_name}"""     )


if __name__ == "__main__":
  __a: Any          =   argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      """--model_name""",
      default="""focalnet-tiny""",
      type=str,
      help="""Name of the FocalNet 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 to push the model and processor to the hub.""",
  )

  __a: str          =   parser.parse_args()
  convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)





"""simple docstring"""
import pytest

import datasets


# Import fixture modules as plugins
SCREAMING_SNAKE_CASE :    List[Any]									=				["""tests.fixtures.files""", """tests.fixtures.hub""", """tests.fixtures.fsspec"""]






def 		lowercase							(     _snake_case						:      Optional[int]     ,   _snake_case						:      Optional[int]     )     ->Tuple:
	"""simple docstring"""





	for item in items:
		if any(marker in item.keywords for marker in ['''integration''', '''unit''']     ):
			continue
		item.add_marker(pytest.mark.unit     )






def 		lowercase							(     _snake_case						:      List[str]     )     ->Optional[int]:
	"""simple docstring"""





	config.addinivalue_line('''markers'''     ,   '''torchaudio_latest: mark test to run with torchaudio>=0.12'''     )






@pytest.fixture(autouse=_snake_case     )
def 		lowercase							(     _snake_case						:      Optional[Any]     ,   _snake_case						:      Dict     )     ->Any:
	"""simple docstring"""





	__snake_case	:						List[Any]						=				tmp_path_factory.getbasetemp() / '''cache'''
	__snake_case	:						int						=				test_hf_cache_home / '''datasets'''
	__snake_case	:						Tuple						=				test_hf_cache_home / '''metrics'''
	__snake_case	:						List[str]						=				test_hf_cache_home / '''modules'''
	monkeypatch.setattr('''datasets.config.HF_DATASETS_CACHE'''     ,   str(_snake_case     )     )
	monkeypatch.setattr('''datasets.config.HF_METRICS_CACHE'''     ,   str(_snake_case     )     )
	monkeypatch.setattr('''datasets.config.HF_MODULES_CACHE'''     ,   str(_snake_case     )     )
	__snake_case	:						Optional[int]						=				test_hf_datasets_cache / '''downloads'''
	monkeypatch.setattr('''datasets.config.DOWNLOADED_DATASETS_PATH'''     ,   str(_snake_case     )     )
	__snake_case	:						Tuple						=				test_hf_datasets_cache / '''downloads''' / '''extracted'''
	monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH'''     ,   str(_snake_case     )     )






@pytest.fixture(autouse=_snake_case     ,   scope='''session'''     )
def 		lowercase							(     )     ->Any:
	"""simple docstring"""





	datasets.disable_progress_bar()






@pytest.fixture(autouse=_snake_case     )
def 		lowercase							(     _snake_case						:      Tuple     )     ->Union[str, Any]:
	"""simple docstring"""





	monkeypatch.setattr('''datasets.config.HF_UPDATE_DOWNLOAD_COUNTS'''     ,   _snake_case     )






@pytest.fixture
def 		lowercase							(     _snake_case						:      Any     )     ->Optional[Any]:
	"""simple docstring"""





	monkeypatch.setattr('''sqlalchemy.util.deprecations.SILENCE_UBER_WARNING'''     ,   _snake_case     )





