


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      snake_case_						( __lowercase       ):
   UpperCAmelCase_							:      Union[str, Any]						=   [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 1_8, 2]
   UpperCAmelCase_							:      List[Any]						=   True if '''large''' in model_name or '''huge''' in model_name else False
   UpperCAmelCase_							:      Tuple						=   True if '''large''' in model_name or '''huge''' in model_name else False
   UpperCAmelCase_							:      List[Any]						=   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:
         UpperCAmelCase_							:      List[Any]						=   [3, 3, 3, 3]
         UpperCAmelCase_							:      Union[str, Any]						=   [5, 5, 5, 5]
      elif "fl4" in model_name:
         UpperCAmelCase_							:      Tuple						=   [4, 4, 4, 4]
         UpperCAmelCase_							:      List[str]						=   [3, 3, 3, 3]

   if "tiny" in model_name or "small" in model_name or "base" in model_name:
      UpperCAmelCase_							:      Tuple						=   [3, 3, 3, 3]
      if "lrf" in model_name:
         UpperCAmelCase_							:      Dict						=   [3, 3, 3, 3]
      else:
         UpperCAmelCase_							:      Tuple						=   [2, 2, 2, 2]

   if "tiny" in model_name:
      UpperCAmelCase_							:      Optional[int]						=   9_6
   elif "small" in model_name:
      UpperCAmelCase_							:      Tuple						=   9_6
   elif "base" in model_name:
      UpperCAmelCase_							:      Optional[Any]						=   1_2_8
   elif "large" in model_name:
      UpperCAmelCase_							:      int						=   1_9_2
   elif "xlarge" in model_name:
      UpperCAmelCase_							:      Dict						=   2_5_6
   elif "huge" in model_name:
      UpperCAmelCase_							:      Union[str, Any]						=   3_5_2

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

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

   UpperCAmelCase_							:      List[str]						=   FocalNetConfig(
       embed_dim=__lowercase			,       depths=__lowercase			,       focal_levels=__lowercase			,       focal_windows=__lowercase			,       use_conv_embed=__lowercase			,       idalabel=__lowercase			,       labelaid=__lowercase			,       use_post_layernorm=__lowercase			,       use_layerscale=__lowercase			,       )

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

   if name == "norm.weight":
      UpperCAmelCase_							:      Tuple						=   '''layernorm.weight'''
   if name == "norm.bias":
      UpperCAmelCase_							:      Dict						=   '''layernorm.bias'''

   if "head" in name:
      UpperCAmelCase_							:      Tuple						=   name.replace('''head'''			,       '''classifier'''       )
   else:
      UpperCAmelCase_							:      str						=   '''focalnet.''' + name

   return name
def      snake_case_						( __lowercase			,       __lowercase			,       __lowercase=False       ):
   # fmt: off
   UpperCAmelCase_							:      Union[str, 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

   UpperCAmelCase_							:      List[Any]						=   model_name_to_url[model_name]
   print('''Checkpoint URL: '''			,       __lowercase       )
   UpperCAmelCase_							:      List[str]						=   torch.hub.load_state_dict_from_url(__lowercase			,       map_location='''cpu'''       )['''model''']

   # rename keys
   for key in state_dict.copy().keys():
      UpperCAmelCase_							:      int						=   state_dict.pop(__lowercase       )
      UpperCAmelCase_							:      Optional[Any]						=   val

   UpperCAmelCase_							:      Optional[Any]						=   get_focalnet_config(__lowercase       )
   UpperCAmelCase_							:      Optional[int]						=   FocalNetForImageClassification(__lowercase       )
   model.eval()

   # load state dict
   model.load_state_dict(__lowercase       )

   # verify conversion
   UpperCAmelCase_							:      List[str]						=   '''http://images.cocodataset.org/val2017/000000039769.jpg'''

   UpperCAmelCase_							:      Optional[int]						=   BitImageProcessor(
       do_resize=__lowercase			,       size={'''shortest_edge''': 2_5_6}			,       resample=PILImageResampling.BILINEAR			,       do_center_crop=__lowercase			,       crop_size=2_2_4			,       do_normalize=__lowercase			,       image_mean=__lowercase			,       image_std=__lowercase			,       )
   UpperCAmelCase_							:      Optional[Any]						=   Image.open(requests.get(__lowercase			,       stream=__lowercase       ).raw       )
   UpperCAmelCase_							:      Union[str, Any]						=   processor(images=__lowercase			,       return_tensors='''pt'''       )

   UpperCAmelCase_							:      List[str]						=   transforms.Compose(
       [
           transforms.Resize(2_5_6       ),
           transforms.CenterCrop(2_2_4       ),
           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]       ),
       ]       )

   UpperCAmelCase_							:      str						=   image_transforms(__lowercase       ).unsqueeze(0       )

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

   UpperCAmelCase_							:      Union[str, Any]						=   model(**__lowercase       )

   UpperCAmelCase_							:      Any						=   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":
      UpperCAmelCase_							:      List[Any]						=   torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1]       )
   elif model_name == "focalnet-tiny-lrf":
      UpperCAmelCase_							:      Optional[Any]						=   torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5]       )
   elif model_name == "focalnet-small":
      UpperCAmelCase_							:      Optional[Any]						=   torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1]       )
   elif model_name == "focalnet-small-lrf":
      UpperCAmelCase_							:      Union[str, Any]						=   torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1]       )
   elif model_name == "focalnet-base":
      UpperCAmelCase_							:      Any						=   torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0]       )
   elif model_name == "focalnet-base-lrf":
      UpperCAmelCase_							:      List[Any]						=   torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8]       )
   assert torch.allclose(outputs.logits[0, :3]			,       __lowercase			,       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(__lowercase       )
      processor.save_pretrained(__lowercase       )

   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__":
       __UpperCamelCase				:  Optional[int]      					=							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.',
       )

       __UpperCamelCase				:  Tuple      					=							parser.parse_args()
       convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)



# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__UpperCamelCase				:  List[Any]      					=							{
    'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'],
}
try:
       if not is_vision_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase				:  Optional[Any]      					=							['VivitImageProcessor']


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase				:  List[Any]      					=							[
           'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
           'VivitModel',
           'VivitPreTrainedModel',
           'VivitForVideoClassification',
       ]


if TYPE_CHECKING:
       from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig

       try:
              if not is_vision_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .image_processing_vivit import VivitImageProcessor

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_vivit import (
                  VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
                  VivitForVideoClassification,
                  VivitModel,
                  VivitPreTrainedModel,
              )


else:
       import sys

       __UpperCamelCase				:  str      					=							_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)