



"""simple docstring"""





import argparse
import ast
import logging
import os
import sys

import pandas as pd
import torch
from tqdm import tqdm

from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score  # noqa: E402 # isort:skip


__lowerCAmelCase							:       Any          =       logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

transformers_logging.set_verbosity_info()
def 						__lowerCAmelCase    (		__UpperCamelCase   :      List[str]     ):


						'''simple docstring'''






						if "token" in model_name_or_path:
												return "rag_token"
						if "sequence" in model_name_or_path:
												return "rag_sequence"
						if "bart" in model_name_or_path:
												return "bart"
						return None
def 						__lowerCAmelCase    (		__UpperCamelCase   :      Optional[int]       ,			__UpperCamelCase   :      str       ,			__UpperCamelCase   :      List[str]     ):


						'''simple docstring'''






						return max(metric_fn(__UpperCamelCase       ,			__UpperCamelCase     ) for gt in ground_truths     )
def 						__lowerCAmelCase    (		__UpperCamelCase   :      Union[str, Any]       ,			__UpperCamelCase   :      Any       ,			__UpperCamelCase   :      Any     ):


						'''simple docstring'''






						snake_case_ :			Optional[int]            =      [line.strip() for line in open(__UpperCamelCase       ,			"""r"""     ).readlines()]
						snake_case_ :			List[str]            =      []

						if args.gold_data_mode == "qa":
												snake_case_ :			Optional[int]            =      pd.read_csv(__UpperCamelCase       ,			sep="""\t"""       ,			header=__UpperCamelCase     )
												for answer_list in data[1]:
																		snake_case_ :			Dict            =      ast.literal_eval(__UpperCamelCase     )
																		answers.append(__UpperCamelCase     )
						else:
												snake_case_ :			Union[str, Any]            =      [line.strip() for line in open(__UpperCamelCase       ,			"""r"""     ).readlines()]
												snake_case_ :			Dict            =      [[reference] for reference in references]

						snake_case_ :			str            =      0
						for prediction, ground_truths in zip(__UpperCamelCase       ,			__UpperCamelCase     ):
												total += 1
												em += metric_max_over_ground_truths(__UpperCamelCase       ,			__UpperCamelCase       ,			__UpperCamelCase     )
												fa += metric_max_over_ground_truths(__UpperCamelCase       ,			__UpperCamelCase       ,			__UpperCamelCase     )

						snake_case_ :			Union[str, Any]            =      100.0 * em / total
						snake_case_ :			Optional[Any]            =      100.0 * fa / total

						logger.info(F'F1: {fa:.2f}'     )
						logger.info(F'EM: {em:.2f}'     )
def 						__lowerCAmelCase    (		__UpperCamelCase   :      Any       ,			__UpperCamelCase   :      Union[str, Any]       ,			__UpperCamelCase   :      Union[str, Any]     ):


						'''simple docstring'''






						snake_case_ :			int            =      args.k
						snake_case_ :			int            =      [line.strip() for line in open(__UpperCamelCase       ,			"""r"""     ).readlines()]
						snake_case_ :			Dict            =      [line.strip() for line in open(__UpperCamelCase       ,			"""r"""     ).readlines()]

						snake_case_ :			Any            =      0
						for hypo, reference in zip(__UpperCamelCase       ,			__UpperCamelCase     ):
												snake_case_ :			Dict            =      set(hypo.split("""\t"""     )[:k]     )
												snake_case_ :			List[Any]            =      set(reference.split("""\t"""     )     )
												total += 1
												em += len(hypo_provenance & ref_provenance     ) / k

						snake_case_ :			Dict            =      100.0 * em / total
						logger.info(F'Precision@{k}: {em: .2f}'     )
def 						__lowerCAmelCase    (		__UpperCamelCase   :      Optional[Any]       ,			__UpperCamelCase   :      Union[str, Any]       ,			__UpperCamelCase   :      Union[str, Any]     ):


						'''simple docstring'''






						def strip_title(__UpperCamelCase   :      str     ):
												if title.startswith("""\""""     ):
																		snake_case_ :			Union[str, Any]            =      title[1:]
												if title.endswith("""\""""     ):
																		snake_case_ :			Union[str, Any]            =      title[:-1]
												return title

						snake_case_ :			Tuple            =      rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
						    __UpperCamelCase       ,			return_tensors="""pt"""       ,			padding=__UpperCamelCase       ,			truncation=__UpperCamelCase       ,			)["""input_ids"""].to(args.device     )

						snake_case_ :			int            =      rag_model.rag.question_encoder(__UpperCamelCase     )
						snake_case_ :			Union[str, Any]            =      question_enc_outputs[0]

						snake_case_ :			Dict            =      rag_model.retriever(
						    __UpperCamelCase       ,			question_enc_pool_output.cpu().detach().to(torch.floataa     ).numpy()       ,			prefix=rag_model.rag.generator.config.prefix       ,			n_docs=rag_model.config.n_docs       ,			return_tensors="""pt"""       ,			)
						snake_case_ :			Tuple            =      rag_model.retriever.index.get_doc_dicts(result.doc_ids     )
						snake_case_ :			Optional[Any]            =      []
						for docs in all_docs:
												snake_case_ :			List[Any]            =      [strip_title(__UpperCamelCase     ) for title in docs["""title"""]]
												provenance_strings.append("""\t""".join(__UpperCamelCase     )     )
						return provenance_strings
def 						__lowerCAmelCase    (		__UpperCamelCase   :      str       ,			__UpperCamelCase   :      Tuple       ,			__UpperCamelCase   :      Optional[Any]     ):


						'''simple docstring'''






						with torch.no_grad():
												snake_case_ :			int            =      rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
												    __UpperCamelCase       ,			return_tensors="""pt"""       ,			padding=__UpperCamelCase       ,			truncation=__UpperCamelCase     )

												snake_case_ :			List[Any]            =      inputs_dict.input_ids.to(args.device     )
												snake_case_ :			Optional[int]            =      inputs_dict.attention_mask.to(args.device     )
												snake_case_ :			Any            =      rag_model.generate(  # rag_model overwrites generate
												    __UpperCamelCase       ,			attention_mask=__UpperCamelCase       ,			num_beams=args.num_beams       ,			min_length=args.min_length       ,			max_length=args.max_length       ,			early_stopping=__UpperCamelCase       ,			num_return_sequences=1       ,			bad_words_ids=[[0, 0]]       ,			)
												snake_case_ :			Tuple            =      rag_model.retriever.generator_tokenizer.batch_decode(__UpperCamelCase       ,			skip_special_tokens=__UpperCamelCase     )

												if args.print_predictions:
																		for q, a in zip(__UpperCamelCase       ,			__UpperCamelCase     ):
																								logger.info("""Q: {} - A: {}""".format(__UpperCamelCase       ,			__UpperCamelCase     )     )

												return answers
def 						__lowerCAmelCase    (		):


						'''simple docstring'''






						snake_case_ :			Any            =      argparse.ArgumentParser()
						parser.add_argument(
						    """--model_type"""       ,			choices=["""rag_sequence""", """rag_token""", """bart"""]       ,			type=__UpperCamelCase       ,			help=(
						        """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the"""
						        """ model_name_or_path"""
						    )       ,			)
						parser.add_argument(
						    """--index_name"""       ,			default=__UpperCamelCase       ,			choices=["""exact""", """compressed""", """legacy"""]       ,			type=__UpperCamelCase       ,			help="""RAG model retriever type"""       ,			)
						parser.add_argument(
						    """--index_path"""       ,			default=__UpperCamelCase       ,			type=__UpperCamelCase       ,			help="""Path to the retrieval index"""       ,			)
						parser.add_argument("""--n_docs"""       ,			default=5       ,			type=__UpperCamelCase       ,			help="""Number of retrieved docs"""     )
						parser.add_argument(
						    """--model_name_or_path"""       ,			default=__UpperCamelCase       ,			type=__UpperCamelCase       ,			required=__UpperCamelCase       ,			help="""Path to pretrained checkpoints or model identifier from huggingface.co/models"""       ,			)
						parser.add_argument(
						    """--eval_mode"""       ,			choices=["""e2e""", """retrieval"""]       ,			default="""e2e"""       ,			type=__UpperCamelCase       ,			help=(
						        """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates"""
						        """ precision@k."""
						    )       ,			)
						parser.add_argument("""--k"""       ,			default=1       ,			type=__UpperCamelCase       ,			help="""k for the precision@k calculation"""     )
						parser.add_argument(
						    """--evaluation_set"""       ,			default=__UpperCamelCase       ,			type=__UpperCamelCase       ,			required=__UpperCamelCase       ,			help="""Path to a file containing evaluation samples"""       ,			)
						parser.add_argument(
						    """--gold_data_path"""       ,			default=__UpperCamelCase       ,			type=__UpperCamelCase       ,			required=__UpperCamelCase       ,			help="""Path to a tab-separated file with gold samples"""       ,			)
						parser.add_argument(
						    """--gold_data_mode"""       ,			default="""qa"""       ,			type=__UpperCamelCase       ,			choices=["""qa""", """ans"""]       ,			help=(
						        """Format of the gold data file"""
						        """qa - a single line in the following format: question [tab] answer_list"""
						        """ans - a single line of the gold file contains the expected answer string"""
						    )       ,			)
						parser.add_argument(
						    """--predictions_path"""       ,			type=__UpperCamelCase       ,			default="""predictions.txt"""       ,			help="""Name of the predictions file, to be stored in the checkpoints directory"""       ,			)
						parser.add_argument(
						    """--eval_all_checkpoints"""       ,			action="""store_true"""       ,			help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number"""       ,			)
						parser.add_argument(
						    """--eval_batch_size"""       ,			default=8       ,			type=__UpperCamelCase       ,			help="""Batch size per GPU/CPU for evaluation."""       ,			)
						parser.add_argument(
						    """--recalculate"""       ,			help="""Recalculate predictions even if the prediction file exists"""       ,			action="""store_true"""       ,			)
						parser.add_argument(
						    """--num_beams"""       ,			default=4       ,			type=__UpperCamelCase       ,			help="""Number of beams to be used when generating answers"""       ,			)
						parser.add_argument("""--min_length"""       ,			default=1       ,			type=__UpperCamelCase       ,			help="""Min length of the generated answers"""     )
						parser.add_argument("""--max_length"""       ,			default=5_0       ,			type=__UpperCamelCase       ,			help="""Max length of the generated answers"""     )

						parser.add_argument(
						    """--print_predictions"""       ,			action="""store_true"""       ,			help="""If True, prints predictions while evaluating."""       ,			)
						parser.add_argument(
						    """--print_docs"""       ,			action="""store_true"""       ,			help="""If True, prints docs retried while generating."""       ,			)
						snake_case_ :			Dict            =      parser.parse_args()
						snake_case_ :			Any            =      torch.device("""cuda""" if torch.cuda.is_available() else """cpu"""     )
						return args
def 						__lowerCAmelCase    (		__UpperCamelCase   :      Tuple     ):


						'''simple docstring'''






						snake_case_ :			Optional[Any]            =      {}
						if args.model_type is None:
												snake_case_ :			Any            =      infer_model_type(args.model_name_or_path     )
												assert args.model_type is not None
						if args.model_type.startswith("""rag"""     ):
												snake_case_ :			List[Any]            =      RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration
												snake_case_ :			Tuple            =      args.n_docs
												if args.index_name is not None:
																		snake_case_ :			Tuple            =      args.index_name
												if args.index_path is not None:
																		snake_case_ :			Any            =      args.index_path
						else:
												snake_case_ :			Optional[Any]            =      BartForConditionalGeneration

						snake_case_ :			int            =      (
						    [f.path for f in os.scandir(args.model_name_or_path     ) if f.is_dir()]
						    if args.eval_all_checkpoints
						    else [args.model_name_or_path]
						)

						logger.info("""Evaluate the following checkpoints: %s"""       ,			__UpperCamelCase     )

						snake_case_ :			Union[str, Any]            =      get_scores if args.eval_mode == """e2e""" else get_precision_at_k
						snake_case_ :			int            =      evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval

						for checkpoint in checkpoints:
												if os.path.exists(args.predictions_path     ) and (not args.recalculate):
																		logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path     )     )
																		score_fn(__UpperCamelCase       ,			args.predictions_path       ,			args.gold_data_path     )
																		continue

												logger.info("""***** Running evaluation for {} *****""".format(__UpperCamelCase     )     )
												logger.info("""  Batch size = %d"""       ,			args.eval_batch_size     )
												logger.info("""  Predictions will be stored under {}""".format(args.predictions_path     )     )

												if args.model_type.startswith("""rag"""     ):
																		snake_case_ :			Any            =      RagRetriever.from_pretrained(__UpperCamelCase       ,			**__UpperCamelCase     )
																		snake_case_ :			Any            =      model_class.from_pretrained(__UpperCamelCase       ,			retriever=__UpperCamelCase       ,			**__UpperCamelCase     )
																		model.retriever.init_retrieval()
												else:
																		snake_case_ :			int            =      model_class.from_pretrained(__UpperCamelCase       ,			**__UpperCamelCase     )
												model.to(args.device     )

												with open(args.evaluation_set       ,			"""r"""     ) as eval_file, open(args.predictions_path       ,			"""w"""     ) as preds_file:
																		snake_case_ :			List[Any]            =      []
																		for line in tqdm(__UpperCamelCase     ):
																								questions.append(line.strip()     )
																								if len(__UpperCamelCase     ) == args.eval_batch_size:
																														snake_case_ :			Tuple            =      evaluate_batch_fn(__UpperCamelCase       ,			__UpperCamelCase       ,			__UpperCamelCase     )
																														preds_file.write("""\n""".join(__UpperCamelCase     ) + """\n"""     )
																														preds_file.flush()
																														snake_case_ :			Dict            =      []
																		if len(__UpperCamelCase     ) > 0:
																								snake_case_ :			List[str]            =      evaluate_batch_fn(__UpperCamelCase       ,			__UpperCamelCase       ,			__UpperCamelCase     )
																								preds_file.write("""\n""".join(__UpperCamelCase     )     )
																								preds_file.flush()

																		score_fn(__UpperCamelCase       ,			args.predictions_path       ,			args.gold_data_path     )


if __name__ == "__main__":
					__lowerCAmelCase							:       List[str]          =       get_args()
					main(args)








"""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  _SCREAMING_SNAKE_CASE						(      _lowercase		:       List[Any]   )					->Dict:






	'''simple docstring'''






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

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

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

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

	a :						Optional[int]      =							json.load(open(hf_hub_download(_lowercase       ,			_lowercase       ,			repo_type="dataset"   )       ,			"r"   )   )
	a :						str      =							{int(_lowercase   ): v for k, v in idalabel.items()}
	a :						List[str]      =							{v: k for k, v in idalabel.items()}

	a :						Dict      =							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  _SCREAMING_SNAKE_CASE						(      _lowercase		:       List[str]   )					->List[Any]:






	'''simple docstring'''






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

	if name == "norm.weight":
		a :						str      =							"layernorm.weight"
	if name == "norm.bias":
		a :						Optional[Any]      =							"layernorm.bias"

	if "head" in name:
		a :						Tuple      =							name.replace("head"       ,			"classifier"   )
	else:
		a :						int      =							"focalnet." + name

	return name






def  _SCREAMING_SNAKE_CASE						(      _lowercase		:       Tuple       ,			_lowercase		:       Optional[Any]       ,			_lowercase		:       Tuple=False   )					->str:






	'''simple docstring'''






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

	a :						str      =							model_name_to_url[model_name]
	print("Checkpoint URL: "       ,			_lowercase   )
	a :						Any      =							torch.hub.load_state_dict_from_url(_lowercase       ,			map_location="cpu"   )["model"]

	# rename keys
	for key in state_dict.copy().keys():
		a :						Any      =							state_dict.pop(_lowercase   )
		a :						Any      =							val

	a :						Any      =							get_focalnet_config(_lowercase   )
	a :						Optional[int]      =							FocalNetForImageClassification(_lowercase   )
	model.eval()

	# load state dict
	model.load_state_dict(_lowercase   )

	# verify conversion
	a :						Union[str, Any]      =							"http://images.cocodataset.org/val2017/000000039769.jpg"

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

	a :						Optional[int]      =							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]   ),
	    ]   )

	a :						str      =							image_transforms(_lowercase   ).unsqueeze(0   )

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

	a :						Dict      =							model(**_lowercase   )

	a :						List[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":
		a :						Union[str, Any]      =							torch.tensor([0.2166, -0.4368, 0.2191]   )
	elif model_name == "focalnet-tiny-lrf":
		a :						Union[str, Any]      =							torch.tensor([1.1669, 0.0125, -0.1695]   )
	elif model_name == "focalnet-small":
		a :						Dict      =							torch.tensor([0.4917, -0.0430, 0.1341]   )
	elif model_name == "focalnet-small-lrf":
		a :						Dict      =							torch.tensor([-0.2588, -0.5342, -0.2331]   )
	elif model_name == "focalnet-base":
		a :						Any      =							torch.tensor([-0.1655, -0.4090, -0.1730]   )
	elif model_name == "focalnet-base-lrf":
		a :						str      =							torch.tensor([0.5306, -0.0483, -0.3928]   )
	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__":
		a		:					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.''',
		)

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


