



"""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 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Optional[Any]    )  ->       int:





     '''simple docstring'''

     _UpperCAmelCase      :     Optional[int]        =   [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2]
     _UpperCAmelCase      :     List[str]        =   True if "large" in model_name or "huge" in model_name else False
     _UpperCAmelCase      :     List[str]        =   True if "large" in model_name or "huge" in model_name else False
     _UpperCAmelCase      :     Dict        =   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      :     Optional[int]        =   [3, 3, 3, 3]
               _UpperCAmelCase      :     str        =   [5, 5, 5, 5]
          elif "fl4" in model_name:
               _UpperCAmelCase      :     int        =   [4, 4, 4, 4]
               _UpperCAmelCase      :     Tuple        =   [3, 3, 3, 3]

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

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

     # set label information
     _UpperCAmelCase      :     List[str]        =   "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      :     Dict        =   json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__						,  SCREAMING_SNAKE_CASE__						,  repo_type="dataset"    )						,  "r"    )    )
     _UpperCAmelCase      :     Optional[int]        =   {int(SCREAMING_SNAKE_CASE__    ): v for k, v in idalabel.items()}
     _UpperCAmelCase      :     Optional[Any]        =   {v: k for k, v in idalabel.items()}

     _UpperCAmelCase      :     Dict        =   FocalNetConfig(
         embed_dim=SCREAMING_SNAKE_CASE__						,  depths=SCREAMING_SNAKE_CASE__						,  focal_levels=SCREAMING_SNAKE_CASE__						,  focal_windows=SCREAMING_SNAKE_CASE__						,  use_conv_embed=SCREAMING_SNAKE_CASE__						,  idalabel=SCREAMING_SNAKE_CASE__						,  labelaid=SCREAMING_SNAKE_CASE__						,  use_post_layernorm=SCREAMING_SNAKE_CASE__						,  use_layerscale=SCREAMING_SNAKE_CASE__						,  )

     return config

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						int    )  ->       Union[str, Any]:





     '''simple docstring'''

     if "patch_embed.proj" in name:
          _UpperCAmelCase      :     Optional[int]        =   name.replace("patch_embed.proj"						,  "embeddings.patch_embeddings.projection"    )
     if "patch_embed.norm" in name:
          _UpperCAmelCase      :     List[str]        =   name.replace("patch_embed.norm"						,  "embeddings.norm"    )
     if "layers" in name:
          _UpperCAmelCase      :     Any        =   "encoder." + name
     if "encoder.layers" in name:
          _UpperCAmelCase      :     Optional[Any]        =   name.replace("encoder.layers"						,  "encoder.stages"    )
     if "downsample.proj" in name:
          _UpperCAmelCase      :     Optional[int]        =   name.replace("downsample.proj"						,  "downsample.projection"    )
     if "blocks" in name:
          _UpperCAmelCase      :     Union[str, Any]        =   name.replace("blocks"						,  "layers"    )
     if "modulation.f.weight" in name or "modulation.f.bias" in name:
          _UpperCAmelCase      :     int        =   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      :     int        =   "layernorm.weight"
     if name == "norm.bias":
          _UpperCAmelCase      :     Dict        =   "layernorm.bias"

     if "head" in name:
          _UpperCAmelCase      :     Optional[int]        =   name.replace("head"						,  "classifier"    )
     else:
          _UpperCAmelCase      :     Optional[int]        =   "focalnet." + name

     return name

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Any						,  SCREAMING_SNAKE_CASE__     :						Optional[int]						,  SCREAMING_SNAKE_CASE__     :						Union[str, Any]=False    )  ->       Tuple:





     '''simple docstring'''

     _UpperCAmelCase      :     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

     _UpperCAmelCase      :     Optional[int]        =   model_name_to_url[model_name]
     print("Checkpoint URL: "						,  SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     str        =   torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__						,  map_location="cpu"    )["model"]

     # rename keys
     for key in state_dict.copy().keys():
          _UpperCAmelCase      :     Optional[Any]        =   state_dict.pop(SCREAMING_SNAKE_CASE__    )
          _UpperCAmelCase      :     Optional[Any]        =   val

     _UpperCAmelCase      :     List[str]        =   get_focalnet_config(SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     Union[str, Any]        =   FocalNetForImageClassification(SCREAMING_SNAKE_CASE__    )
     model.eval()

     # load state dict
     model.load_state_dict(SCREAMING_SNAKE_CASE__    )

     # verify conversion
     _UpperCAmelCase      :     Tuple        =   "http://images.cocodataset.org/val2017/000000039769.jpg"

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

     _UpperCAmelCase      :     List[Any]        =   transforms.Compose(
         [
             transforms.Resize(256    ),
             transforms.CenterCrop(224    ),
             transforms.ToTensor(),
             transforms.Normalize(mean=[0.485, 0.456, 0.406]						,  std=[0.229, 0.224, 0.225]    ),
         ]    )

     _UpperCAmelCase      :     Optional[int]        =   image_transforms(SCREAMING_SNAKE_CASE__    ).unsqueeze(0    )

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

     _UpperCAmelCase      :     Union[str, Any]        =   model(**SCREAMING_SNAKE_CASE__    )

     _UpperCAmelCase      :     Optional[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      :     Tuple        =   torch.tensor([0.2_166, -0.4_368, 0.2_191]    )
     elif model_name == "focalnet-tiny-lrf":
          _UpperCAmelCase      :     Any        =   torch.tensor([1.1_669, 0.0_125, -0.1_695]    )
     elif model_name == "focalnet-small":
          _UpperCAmelCase      :     Dict        =   torch.tensor([0.4_917, -0.0_430, 0.1_341]    )
     elif model_name == "focalnet-small-lrf":
          _UpperCAmelCase      :     Dict        =   torch.tensor([-0.2_588, -0.5_342, -0.2_331]    )
     elif model_name == "focalnet-base":
          _UpperCAmelCase      :     List[Any]        =   torch.tensor([-0.1_655, -0.4_090, -0.1_730]    )
     elif model_name == "focalnet-base-lrf":
          _UpperCAmelCase      :     int        =   torch.tensor([0.5_306, -0.0_483, -0.3_928]    )
     assert torch.allclose(outputs.logits[0, :3]						,  SCREAMING_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(SCREAMING_SNAKE_CASE__    )
          processor.save_pretrained(SCREAMING_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__":
 _lowerCAmelCase    : List[str]							=							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.",
 )

 _lowerCAmelCase    : List[str]							=							parser.parse_args()
 convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)





"""simple docstring"""




import os
import zipfile

import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Tuple						,  SCREAMING_SNAKE_CASE__     :						List[str]=7    )  ->       Tuple:





     '''simple docstring'''

     _UpperCAmelCase      :     Union[str, Any]        =   None
     if token is not None:
          _UpperCAmelCase      :     str        =   {"Accept": "application/vnd.github+json", "Authorization": f'Bearer {token}'}

     # The id of a workflow (not of a workflow run)
     _UpperCAmelCase      :     Any        =   "636036"

     _UpperCAmelCase      :     Dict        =   f'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs'
     # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
     url += f'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}'

     _UpperCAmelCase      :     Tuple        =   requests.get(SCREAMING_SNAKE_CASE__						,  headers=SCREAMING_SNAKE_CASE__    ).json()

     return result["workflow_runs"]

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Union[str, Any]    )  ->       Optional[int]:





     '''simple docstring'''

     _UpperCAmelCase      :     int        =   get_daily_ci_runs(SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     Optional[int]        =   None
     for workflow_run in workflow_runs:
          if workflow_run["status"] == "completed":
               _UpperCAmelCase      :     str        =   workflow_run["id"]
               break

     return workflow_run_id

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Dict						,  SCREAMING_SNAKE_CASE__     :						str						,  SCREAMING_SNAKE_CASE__     :						Union[str, Any]    )  ->       List[str]:





     '''simple docstring'''

     _UpperCAmelCase      :     List[str]        =   get_last_daily_ci_runs(SCREAMING_SNAKE_CASE__    )
     if workflow_run_id is not None:
          _UpperCAmelCase      :     Any        =   get_artifacts_links(worflow_run_id=SCREAMING_SNAKE_CASE__						,  token=SCREAMING_SNAKE_CASE__    )
          for artifact_name in artifact_names:
               if artifact_name in artifacts_links:
                    _UpperCAmelCase      :     List[str]        =   artifacts_links[artifact_name]
                    download_artifact(
                        artifact_name=SCREAMING_SNAKE_CASE__						,  artifact_url=SCREAMING_SNAKE_CASE__						,  output_dir=SCREAMING_SNAKE_CASE__						,  token=SCREAMING_SNAKE_CASE__    )

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Tuple						,  SCREAMING_SNAKE_CASE__     :						Dict						,  SCREAMING_SNAKE_CASE__     :						Union[str, Any]    )  ->       Union[str, Any]:





     '''simple docstring'''

     get_last_daily_ci_artifacts(SCREAMING_SNAKE_CASE__						,  SCREAMING_SNAKE_CASE__						,  SCREAMING_SNAKE_CASE__    )

     _UpperCAmelCase      :     Any        =   {}
     for artifact_name in artifact_names:
          _UpperCAmelCase      :     Dict        =   os.path.join(SCREAMING_SNAKE_CASE__						,  f'{artifact_name}.zip'    )
          if os.path.isfile(SCREAMING_SNAKE_CASE__    ):
               _UpperCAmelCase      :     str        =   {}
               with zipfile.ZipFile(SCREAMING_SNAKE_CASE__    ) as z:
                    for filename in z.namelist():
                         if not os.path.isdir(SCREAMING_SNAKE_CASE__    ):
                              # read the file
                              with z.open(SCREAMING_SNAKE_CASE__    ) as f:
                                   _UpperCAmelCase      :     List[str]        =   f.read().decode("UTF-8"    )

     return results
