


"""simple docstring"""
import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image

from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
__SCREAMING_SNAKE_CASE				:     List[str]		=     logging.get_logger(__name__)







def     _a					(   )     ->					List[str]:
							snake_case_     							=		DetaConfig(
							    num_queries=900					,			encoder_ffn_dim=2_048					,			decoder_ffn_dim=2_048					,			num_feature_levels=5					,			assign_first_stage=_SCREAMING_SNAKE_CASE					,			with_box_refine=_SCREAMING_SNAKE_CASE					,			two_stage=_SCREAMING_SNAKE_CASE					,			)

							# set labels
							snake_case_     							=		91
							snake_case_     							=		"""huggingface/label-files"""
							snake_case_     							=		"""coco-detection-id2label.json"""
							snake_case_     							=		json.load(open(cached_download(hf_hub_url(_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			repo_type="""dataset"""					)					)					,			"""r"""					)					)
							snake_case_     							=		{int(_SCREAMING_SNAKE_CASE					): v for k, v in idalabel.items()}
							snake_case_     							=		idalabel
							snake_case_     							=		{v: k for k, v in idalabel.items()}

							return config







def     _a					(   _SCREAMING_SNAKE_CASE					)     ->					int:
							snake_case_     							=		[]

							# stem
							# fmt: off
							rename_keys.append(("""backbone.0.body.conv1.weight""", """model.backbone.model.embedder.embedder.convolution.weight""")					)
							rename_keys.append(("""backbone.0.body.bn1.weight""", """model.backbone.model.embedder.embedder.normalization.weight""")					)
							rename_keys.append(("""backbone.0.body.bn1.bias""", """model.backbone.model.embedder.embedder.normalization.bias""")					)
							rename_keys.append(("""backbone.0.body.bn1.running_mean""", """model.backbone.model.embedder.embedder.normalization.running_mean""")					)
							rename_keys.append(("""backbone.0.body.bn1.running_var""", """model.backbone.model.embedder.embedder.normalization.running_var""")					)
							# stages
							for stage_idx in range(len(config.backbone_config.depths					)					):
														for layer_idx in range(config.backbone_config.depths[stage_idx]					):
																					# shortcut
																					if layer_idx == 0:
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight""",
																												    )					)
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight""",
																												    )					)
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias""",
																												    )					)
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean""",
																												    )					)
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var""",
																												    )					)
																					# 3 convs
																					for i in range(3					):
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight""",
																												    )					)
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight""",
																												    )					)
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias""",
																												    )					)
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean""",
																												    )					)
																												rename_keys.append(
																												    (
																												        f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var""",
																												        f"""model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var""",
																												    )					)
    # transformer encoder
							for i in range(config.encoder_layers					):
														rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight""", f"""model.encoder.layers.{i}.self_attn.sampling_offsets.weight""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias""", f"""model.encoder.layers.{i}.self_attn.sampling_offsets.bias""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.attention_weights.weight""", f"""model.encoder.layers.{i}.self_attn.attention_weights.weight""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.attention_weights.bias""", f"""model.encoder.layers.{i}.self_attn.attention_weights.bias""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.value_proj.weight""", f"""model.encoder.layers.{i}.self_attn.value_proj.weight""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.value_proj.bias""", f"""model.encoder.layers.{i}.self_attn.value_proj.bias""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.output_proj.weight""", f"""model.encoder.layers.{i}.self_attn.output_proj.weight""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.output_proj.bias""", f"""model.encoder.layers.{i}.self_attn.output_proj.bias""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.weight""", f"""model.encoder.layers.{i}.self_attn_layer_norm.weight""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.bias""", f"""model.encoder.layers.{i}.self_attn_layer_norm.bias""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""model.encoder.layers.{i}.fc1.weight""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""model.encoder.layers.{i}.fc1.bias""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""model.encoder.layers.{i}.fc2.weight""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""model.encoder.layers.{i}.fc2.bias""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.weight""", f"""model.encoder.layers.{i}.final_layer_norm.weight""")					)
														rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""model.encoder.layers.{i}.final_layer_norm.bias""")					)

							# transformer decoder
							for i in range(config.decoder_layers					):
														rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight""", f"""model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias""", f"""model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.attention_weights.weight""", f"""model.decoder.layers.{i}.encoder_attn.attention_weights.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.attention_weights.bias""", f"""model.decoder.layers.{i}.encoder_attn.attention_weights.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.value_proj.weight""", f"""model.decoder.layers.{i}.encoder_attn.value_proj.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.value_proj.bias""", f"""model.decoder.layers.{i}.encoder_attn.value_proj.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.output_proj.weight""", f"""model.decoder.layers.{i}.encoder_attn.output_proj.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.output_proj.bias""", f"""model.decoder.layers.{i}.encoder_attn.output_proj.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.weight""", f"""model.decoder.layers.{i}.encoder_attn_layer_norm.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.bias""", f"""model.decoder.layers.{i}.encoder_attn_layer_norm.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""model.decoder.layers.{i}.self_attn.out_proj.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""model.decoder.layers.{i}.self_attn.out_proj.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.norm2.weight""", f"""model.decoder.layers.{i}.self_attn_layer_norm.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.norm2.bias""", f"""model.decoder.layers.{i}.self_attn_layer_norm.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""model.decoder.layers.{i}.fc1.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""model.decoder.layers.{i}.fc1.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""model.decoder.layers.{i}.fc2.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""model.decoder.layers.{i}.fc2.bias""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.weight""", f"""model.decoder.layers.{i}.final_layer_norm.weight""")					)
														rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""model.decoder.layers.{i}.final_layer_norm.bias""")					)

							# fmt: on

							return rename_keys







def     _a					(   _SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)     ->					int:
							snake_case_     							=		dct.pop(_SCREAMING_SNAKE_CASE					)
							snake_case_     							=		val







def     _a					(   _SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)     ->					List[Any]:
							# transformer decoder self-attention layers
							snake_case_     							=		config.d_model
							for i in range(config.decoder_layers					):
														# read in weights + bias of input projection layer of self-attention
														snake_case_     							=		state_dict.pop(f"""transformer.decoder.layers.{i}.self_attn.in_proj_weight"""					)
														snake_case_     							=		state_dict.pop(f"""transformer.decoder.layers.{i}.self_attn.in_proj_bias"""					)
														# next, add query, keys and values (in that order) to the state dict
														snake_case_     							=		in_proj_weight[:hidden_size, :]
														snake_case_     							=		in_proj_bias[:hidden_size]
														snake_case_     							=		in_proj_weight[
														    hidden_size : hidden_size * 2, :
														]
														snake_case_     							=		in_proj_bias[hidden_size : hidden_size * 2]
														snake_case_     							=		in_proj_weight[-hidden_size:, :]
														snake_case_     							=		in_proj_bias[-hidden_size:]







def     _a					(   )     ->					Optional[int]:
							snake_case_     							=		"""http://images.cocodataset.org/val2017/000000039769.jpg"""
							snake_case_     							=		Image.open(requests.get(_SCREAMING_SNAKE_CASE					,			stream=_SCREAMING_SNAKE_CASE					).raw					)

							return im







@torch.no_grad()
def     _a					(   _SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)     ->					Tuple:
							snake_case_     							=		get_deta_config()

							# load original state dict
							if model_name == "deta-resnet-50":
														snake_case_     							=		"""adet_checkpoint0011.pth"""
							elif model_name == "deta-resnet-50-24-epochs":
														snake_case_     							=		"""adet_2x_checkpoint0023.pth"""
							else:
														raise ValueError(f"""Model name {model_name} not supported"""					)
							snake_case_     							=		hf_hub_download(repo_id="""nielsr/deta-checkpoints"""					,			filename=_SCREAMING_SNAKE_CASE					)
							snake_case_     							=		torch.load(_SCREAMING_SNAKE_CASE					,			map_location="""cpu"""					)["""model"""]

							# rename keys
							snake_case_     							=		create_rename_keys(_SCREAMING_SNAKE_CASE					)
							for src, dest in rename_keys:
														rename_key(_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)
							read_in_decoder_q_k_v(_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)

							# fix some prefixes
							for key in state_dict.copy().keys():
														if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
																					snake_case_     							=		state_dict.pop(_SCREAMING_SNAKE_CASE					)
																					snake_case_     							=		val
														if "input_proj" in key:
																					snake_case_     							=		state_dict.pop(_SCREAMING_SNAKE_CASE					)
																					snake_case_     							=		val
														if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
																					snake_case_     							=		state_dict.pop(_SCREAMING_SNAKE_CASE					)
																					snake_case_     							=		val

    # finally, create HuggingFace model and load state dict
							snake_case_     							=		DetaForObjectDetection(_SCREAMING_SNAKE_CASE					)
							model.load_state_dict(_SCREAMING_SNAKE_CASE					)
							model.eval()

							snake_case_     							=		"""cuda""" if torch.cuda.is_available() else """cpu"""
							model.to(_SCREAMING_SNAKE_CASE					)

							# load image processor
							snake_case_     							=		DetaImageProcessor(format="""coco_detection"""					)

							# verify our conversion on image
							snake_case_     							=		prepare_img()
							snake_case_     							=		processor(images=_SCREAMING_SNAKE_CASE					,			return_tensors="""pt"""					)
							snake_case_     							=		encoding["""pixel_values"""]
							snake_case_     							=		model(pixel_values.to(_SCREAMING_SNAKE_CASE					)					)

							# verify logits
							if model_name == "deta-resnet-50":
														snake_case_     							=		torch.tensor(
														    [[-7.3978, -2.5406, -4.1668], [-8.2684, -3.9933, -3.8096], [-7.0515, -3.7973, -5.8516]]					)
														snake_case_     							=		torch.tensor([[0.5043, 0.4973, 0.9998], [0.2542, 0.5489, 0.4748], [0.5490, 0.2765, 0.0570]]					)
							elif model_name == "deta-resnet-50-24-epochs":
														snake_case_     							=		torch.tensor(
														    [[-7.1688, -2.4857, -4.8669], [-7.8630, -3.8154, -4.2674], [-7.2730, -4.1865, -5.5323]]					)
														snake_case_     							=		torch.tensor([[0.5021, 0.4971, 0.9994], [0.2546, 0.5486, 0.4731], [0.1686, 0.1986, 0.2142]]					)

							assert torch.allclose(outputs.logits[0, :3, :3]					,			expected_logits.to(_SCREAMING_SNAKE_CASE					)					,			atol=1E-4					)
							assert torch.allclose(outputs.pred_boxes[0, :3, :3]					,			expected_boxes.to(_SCREAMING_SNAKE_CASE					)					,			atol=1E-4					)
							print("""Everything ok!"""					)

							if pytorch_dump_folder_path:
														# Save model and processor
														logger.info(f"""Saving PyTorch model and processor to {pytorch_dump_folder_path}..."""					)
														Path(_SCREAMING_SNAKE_CASE					).mkdir(exist_ok=_SCREAMING_SNAKE_CASE					)
														model.save_pretrained(_SCREAMING_SNAKE_CASE					)
														processor.save_pretrained(_SCREAMING_SNAKE_CASE					)

							# Push to hub
							if push_to_hub:
														print("""Pushing model and processor to hub..."""					)
														model.push_to_hub(f"""jozhang97/{model_name}"""					)
														processor.push_to_hub(f"""jozhang97/{model_name}"""					)


if __name__ == "__main__":
				__SCREAMING_SNAKE_CASE				:     List[str]		=     argparse.ArgumentParser()

				parser.add_argument(
				    '--model_name',
				    type=str,
				    default='deta-resnet-50',
				    choices=['deta-resnet-50', 'deta-resnet-50-24-epochs'],
				    help='Name of the model you\'d like to convert.',
				)
				parser.add_argument(
				    '--pytorch_dump_folder_path',
				    default=None,
				    type=str,
				    help='Path to the folder to output PyTorch model.',
				)
				parser.add_argument(
				    '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
				)
				__SCREAMING_SNAKE_CASE				:     List[str]		=     parser.parse_args()
				convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)







"""simple docstring"""
from __future__ import annotations

from collections import deque
from enum import Enum
from math import atana, degrees
from sys import maxsize





class   __A  (snake_case__):





							'''simple docstring'''

							__lowercase:		Dict				   =     1
							__lowercase:		List[str]				   =     2
							__lowercase:		int				   =     3



							def __repr__(					self				:   Optional[Any]							)       ->Optional[int]:



														"""simple docstring"""



														return F"""{self.__class__.__name__}.{self.name}"""







def     _a					(   _SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)     ->					float:
							snake_case_							,    snake_case_     							=		point
							return degrees(atana(y - miny					,			x - minx					)					)







def     _a					(   _SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)     ->					Direction:
							snake_case_							,    snake_case_     							=		starting
							snake_case_							,    snake_case_     							=		via
							snake_case_							,    snake_case_     							=		target
							snake_case_     							=		degrees(atana(ya - ya					,			xa - xa					)					)
							via_angle %= 360
							snake_case_     							=		degrees(atana(ya - ya					,			xa - xa					)					)
							target_angle %= 360
							# t-
							#  \ \
							#   \ v
							#    \|
							#     s
							# via_angle is always lower than target_angle, if direction is left.
							# If they are same, it means they are on a same line of convex hull.
							if target_angle > via_angle:
														return Direction.left
							elif target_angle == via_angle:
														return Direction.straight
							else:
														return Direction.right







def     _a					(   _SCREAMING_SNAKE_CASE					)     ->					list[tuple[int, int]]:

							if len(_SCREAMING_SNAKE_CASE					) <= 2:
														# There is no convex hull
														raise ValueError("""graham_scan: argument must contain more than 3 points."""					)
							if len(_SCREAMING_SNAKE_CASE					) == 3:
														return points
							# find the lowest and the most left point
							snake_case_     							=		0
							snake_case_							,    snake_case_     							=		maxsize, maxsize
							for i, point in enumerate(_SCREAMING_SNAKE_CASE					):
														snake_case_     							=		point[0]
														snake_case_     							=		point[1]
														if y < miny:
																					snake_case_     							=		y
																					snake_case_     							=		x
																					snake_case_     							=		i
														if y == miny and x < minx:
																					snake_case_     							=		x
																					snake_case_     							=		i

    # remove the lowest and the most left point from points for preparing for sort
							points.pop(_SCREAMING_SNAKE_CASE					)

							snake_case_     							=		sorted(_SCREAMING_SNAKE_CASE					,			key=lambda _SCREAMING_SNAKE_CASE					: angle_comparer(_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)					)
							# This insert actually costs complexity,
							# and you should instead add (minx, miny) into stack later.
							# I'm using insert just for easy understanding.
							sorted_points.insert(0					,			(minx, miny)					)

							snake_case_     							=		deque()
							stack.append(sorted_points[0]					)
							stack.append(sorted_points[1]					)
							stack.append(sorted_points[2]					)
							# In any ways, the first 3 points line are towards left.
							# Because we sort them the angle from minx, miny.
							snake_case_     							=		Direction.left

							for i in range(3					,			len(_SCREAMING_SNAKE_CASE					)					):
														while True:
																					snake_case_     							=		stack[-2]
																					snake_case_     							=		stack[-1]
																					snake_case_     							=		sorted_points[i]
																					snake_case_     							=		check_direction(_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					)

																					if next_direction == Direction.left:
																												snake_case_     							=		Direction.left
																												break
																					if next_direction == Direction.straight:
																												if current_direction == Direction.left:
																																			# We keep current_direction as left.
																																			# Because if the straight line keeps as straight,
																																			# we want to know if this straight line is towards left.
																																			break
																												elif current_direction == Direction.right:
																																			# If the straight line is towards right,
																																			# every previous points on those straigh line is not convex hull.
																																			stack.pop()
																					if next_direction == Direction.right:
																												stack.pop()
														stack.append(sorted_points[i]					)
							return list(_SCREAMING_SNAKE_CASE					)



