






"""simple docstring"""



import argparse
import os

import align
import numpy as np
import requests
import tensorflow as tf
import torch
from PIL import Image
from tokenizer import Tokenizer

from transformers import (
    AlignConfig,
    AlignModel,
    AlignProcessor,
    BertConfig,
    BertTokenizer,
    EfficientNetConfig,
    EfficientNetImageProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
_snake_case       :      Dict       =					logging.get_logger(__name__)




def 						lowerCamelCase_				(  __A  :		Tuple			):
					lowerCamelCase__				=tf.image.resize(__A			,	(346, 346)			)
					lowerCamelCase__				=tf.image.crop_to_bounding_box(__A			,	(346 - 289) // 2			,	(346 - 289) // 2			,	289			,	289			)
					return image




def 						lowerCamelCase_				(  ):
					lowerCamelCase__				=EfficientNetConfig.from_pretrained('google/efficientnet-b7'			)
					lowerCamelCase__				=289
					lowerCamelCase__				=640
					lowerCamelCase__				={'0': 'LABEL_0', '1': 'LABEL_1'}
					lowerCamelCase__				={'LABEL_0': 0, 'LABEL_1': 1}
					lowerCamelCase__				=[]

					lowerCamelCase__				=BertConfig()
					lowerCamelCase__				=AlignConfig.from_text_vision_configs(
					    text_config=__A			,	vision_config=__A			,	projection_dim=640			)
					return config




def 						lowerCamelCase_				(  ):
					lowerCamelCase__				='http://images.cocodataset.org/val2017/000000039769.jpg'
					lowerCamelCase__				=Image.open(requests.get(__A			,	stream=__A			).raw			)
					return im




def 						lowerCamelCase_				(  ):
					lowerCamelCase__				=EfficientNetImageProcessor(
					    do_center_crop=__A			,	rescale_factor=1 / 127.5			,	rescale_offset=__A			,	do_normalize=__A			,	include_top=__A			,	resample=Image.BILINEAR			,	)
					lowerCamelCase__				=BertTokenizer.from_pretrained('bert-base-uncased'			)
					lowerCamelCase__				=64
					lowerCamelCase__				=AlignProcessor(image_processor=__A			,	tokenizer=__A			)
					return processor




def 						lowerCamelCase_				(  __A  :		Union[str, Any]			):
					# EfficientNet image encoder
					lowerCamelCase__				=[v.split('_'			)[0].split('block'			)[1] for v in original_param_names if v.startswith('block'			)]
					lowerCamelCase__				=list(set(__A			)			)
					lowerCamelCase__				=sorted(__A			)
					lowerCamelCase__				=len(__A			)
					lowerCamelCase__				={b: str(__A			) for b, i in zip(__A			,	range(__A			)			)}

					lowerCamelCase__				=[]
					rename_keys.append(('stem_conv/kernel:0', 'embeddings.convolution.weight')			)
					rename_keys.append(('stem_bn/gamma:0', 'embeddings.batchnorm.weight')			)
					rename_keys.append(('stem_bn/beta:0', 'embeddings.batchnorm.bias')			)
					rename_keys.append(('stem_bn/moving_mean:0', 'embeddings.batchnorm.running_mean')			)
					rename_keys.append(('stem_bn/moving_variance:0', 'embeddings.batchnorm.running_var')			)

					for b in block_names:
										lowerCamelCase__				=block_name_mapping[b]
										rename_keys.append((f"block{b}_expand_conv/kernel:0", f"encoder.blocks.{hf_b}.expansion.expand_conv.weight")			)
										rename_keys.append((f"block{b}_expand_bn/gamma:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.weight")			)
										rename_keys.append((f"block{b}_expand_bn/beta:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.bias")			)
										rename_keys.append(
										    (f"block{b}_expand_bn/moving_mean:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_mean")			)
										rename_keys.append(
										    (f"block{b}_expand_bn/moving_variance:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_var")			)
										rename_keys.append(
										    (f"block{b}_dwconv/depthwise_kernel:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight")			)
										rename_keys.append((f"block{b}_bn/gamma:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight")			)
										rename_keys.append((f"block{b}_bn/beta:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias")			)
										rename_keys.append(
										    (f"block{b}_bn/moving_mean:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean")			)
										rename_keys.append(
										    (f"block{b}_bn/moving_variance:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var")			)

										rename_keys.append((f"block{b}_se_reduce/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.weight")			)
										rename_keys.append((f"block{b}_se_reduce/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.bias")			)
										rename_keys.append((f"block{b}_se_expand/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.weight")			)
										rename_keys.append((f"block{b}_se_expand/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.bias")			)
										rename_keys.append(
										    (f"block{b}_project_conv/kernel:0", f"encoder.blocks.{hf_b}.projection.project_conv.weight")			)
										rename_keys.append((f"block{b}_project_bn/gamma:0", f"encoder.blocks.{hf_b}.projection.project_bn.weight")			)
										rename_keys.append((f"block{b}_project_bn/beta:0", f"encoder.blocks.{hf_b}.projection.project_bn.bias")			)
										rename_keys.append(
										    (f"block{b}_project_bn/moving_mean:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_mean")			)
										rename_keys.append(
										    (f"block{b}_project_bn/moving_variance:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_var")			)

					lowerCamelCase__				={}
					for item in rename_keys:
										if item[0] in original_param_names:
															lowerCamelCase__				='vision_model.' + item[1]

    # BERT text encoder
					lowerCamelCase__				=[]
					lowerCamelCase__				='tf_bert_model/bert'
					lowerCamelCase__				='text_model'
					for i in range(12			):
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/query/kernel:0",
										        f"{new}.encoder.layer.{i}.attention.self.query.weight",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/query/bias:0",
										        f"{new}.encoder.layer.{i}.attention.self.query.bias",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/key/kernel:0",
										        f"{new}.encoder.layer.{i}.attention.self.key.weight",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/key/bias:0",
										        f"{new}.encoder.layer.{i}.attention.self.key.bias",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/value/kernel:0",
										        f"{new}.encoder.layer.{i}.attention.self.value.weight",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/self/value/bias:0",
										        f"{new}.encoder.layer.{i}.attention.self.value.bias",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/output/dense/kernel:0",
										        f"{new}.encoder.layer.{i}.attention.output.dense.weight",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/output/dense/bias:0",
										        f"{new}.encoder.layer.{i}.attention.output.dense.bias",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/gamma:0",
										        f"{new}.encoder.layer.{i}.attention.output.LayerNorm.weight",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/beta:0",
										        f"{new}.encoder.layer.{i}.attention.output.LayerNorm.bias",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/intermediate/dense/kernel:0",
										        f"{new}.encoder.layer.{i}.intermediate.dense.weight",
										    )			)
										rename_keys.append(
										    (
										        f"{old}/encoder/layer_._{i}/intermediate/dense/bias:0",
										        f"{new}.encoder.layer.{i}.intermediate.dense.bias",
										    )			)
										rename_keys.append(
										    (f"{old}/encoder/layer_._{i}/output/dense/kernel:0", f"{new}.encoder.layer.{i}.output.dense.weight")			)
										rename_keys.append(
										    (f"{old}/encoder/layer_._{i}/output/dense/bias:0", f"{new}.encoder.layer.{i}.output.dense.bias")			)
										rename_keys.append(
										    (f"{old}/encoder/layer_._{i}/output/LayerNorm/gamma:0", f"{new}.encoder.layer.{i}.output.LayerNorm.weight")			)
										rename_keys.append(
										    (f"{old}/encoder/layer_._{i}/output/LayerNorm/beta:0", f"{new}.encoder.layer.{i}.output.LayerNorm.bias")			)

					rename_keys.append((f"{old}/embeddings/word_embeddings/weight:0", f"{new}.embeddings.word_embeddings.weight")			)
					rename_keys.append(
					    (f"{old}/embeddings/position_embeddings/embeddings:0", f"{new}.embeddings.position_embeddings.weight")			)
					rename_keys.append(
					    (f"{old}/embeddings/token_type_embeddings/embeddings:0", f"{new}.embeddings.token_type_embeddings.weight")			)
					rename_keys.append((f"{old}/embeddings/LayerNorm/gamma:0", f"{new}.embeddings.LayerNorm.weight")			)
					rename_keys.append((f"{old}/embeddings/LayerNorm/beta:0", f"{new}.embeddings.LayerNorm.bias")			)

					rename_keys.append((f"{old}/pooler/dense/kernel:0", f"{new}.pooler.dense.weight")			)
					rename_keys.append((f"{old}/pooler/dense/bias:0", f"{new}.pooler.dense.bias")			)
					rename_keys.append(('dense/kernel:0', 'text_projection.weight')			)
					rename_keys.append(('dense/bias:0', 'text_projection.bias')			)
					rename_keys.append(('dense/bias:0', 'text_projection.bias')			)
					rename_keys.append(('temperature:0', 'temperature')			)

					for item in rename_keys:
										if item[0] in original_param_names:
															lowerCamelCase__				=item[1]
					return key_mapping




def 						lowerCamelCase_				(  __A  :		List[Any]			,	__A  :		Dict			,	__A  :		str			):
					list(hf_params.keys()			)

					for key, value in tf_params.items():
										if key not in key_mapping:
															continue

										lowerCamelCase__				=key_mapping[key]
										if "_conv" in key and "kernel" in key:
															lowerCamelCase__				=torch.from_numpy(__A			).permute(3			,	2			,	0			,	1			)
										elif "embeddings" in key:
															lowerCamelCase__				=torch.from_numpy(__A			)
										elif "depthwise_kernel" in key:
															lowerCamelCase__				=torch.from_numpy(__A			).permute(2			,	3			,	0			,	1			)
										elif "kernel" in key:
															lowerCamelCase__				=torch.from_numpy(np.transpose(__A			)			)
										elif "temperature" in key:
															lowerCamelCase__				=value
										elif "bn/gamma" or "bn/beta" in key:
															lowerCamelCase__				=torch.from_numpy(np.transpose(__A			)			).squeeze()
										else:
															lowerCamelCase__				=torch.from_numpy(__A			)

										# Replace HF parameters with original TF model parameters
										hf_params[hf_key].copy_(__A			)




@torch.no_grad()
def 						lowerCamelCase_				(  __A  :		List[str]			,	__A  :		Union[str, Any]			,	__A  :		str			,	__A  :		int			):
					lowerCamelCase__				=64
					lowerCamelCase__				=Tokenizer(__A			)
					lowerCamelCase__				=align.Align('efficientnet-b7'			,	'bert-base'			,	640			,	__A			,	tok.get_vocab_size()			)
					original_model.compile()
					original_model.load_weights(__A			)

					lowerCamelCase__				=original_model.trainable_variables
					lowerCamelCase__				=original_model.non_trainable_variables
					lowerCamelCase__				={param.name: param.numpy() for param in tf_params}
					for param in tf_non_train_params:
										lowerCamelCase__				=param.numpy()
					lowerCamelCase__				=list(tf_params.keys()			)

					# Load HuggingFace model
					lowerCamelCase__				=get_align_config()
					lowerCamelCase__				=AlignModel(__A			).eval()
					lowerCamelCase__				=hf_model.state_dict()

					# Create src-to-dst parameter name mapping dictionary
					print('Converting parameters...'			)
					lowerCamelCase__				=rename_keys(__A			)
					replace_params(__A			,	__A			,	__A			)

					# Initialize processor
					lowerCamelCase__				=get_processor()
					lowerCamelCase__				=processor(
					    images=prepare_img()			,	text='A picture of a cat'			,	padding='max_length'			,	max_length=64			,	return_tensors='pt'			)

					# HF model inference
					hf_model.eval()
					with torch.no_grad():
										lowerCamelCase__				=hf_model(**__A			)

					lowerCamelCase__				=outputs.image_embeds.detach().numpy()
					lowerCamelCase__				=outputs.text_embeds.detach().numpy()

					# Original model inference
					lowerCamelCase__				=False
					lowerCamelCase__				=EfficientNetImageProcessor(
					    do_center_crop=__A			,	do_rescale=__A			,	do_normalize=__A			,	include_top=__A			,	resample=Image.BILINEAR			,	)
					lowerCamelCase__				=tf_image_processor(images=prepare_img()			,	return_tensors='tf'			,	data_format='channels_last'			)['pixel_values']
					lowerCamelCase__				=tok(tf.constant(['A picture of a cat']			)			)

					lowerCamelCase__				=original_model.image_encoder(__A			,	training=__A			)
					lowerCamelCase__				=original_model.text_encoder(__A			,	training=__A			)

					lowerCamelCase__				=tf.nn.la_normalize(__A			,	axis=-1			)
					lowerCamelCase__				=tf.nn.la_normalize(__A			,	axis=-1			)

					# Check whether original and HF model outputs match  -> np.allclose
					if not np.allclose(__A			,	__A			,	atol=1E-3			):
										raise ValueError('The predicted image features are not the same.'			)
					if not np.allclose(__A			,	__A			,	atol=1E-3			):
										raise ValueError('The predicted text features are not the same.'			)
					print('Model outputs match!'			)

					if save_model:
										# Create folder to save model
										if not os.path.isdir(__A			):
															os.mkdir(__A			)
										# Save converted model and image processor
										hf_model.save_pretrained(__A			)
										processor.save_pretrained(__A			)

					if push_to_hub:
										# Push model and image processor to hub
										print('Pushing converted ALIGN to the hub...'			)
										processor.push_to_hub('align-base'			)
										hf_model.push_to_hub('align-base'			)


if __name__ == "__main__":
						_snake_case       :      int       =					argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    "--checkpoint_path",
						    default="./weights/model-weights",
						    type=str,
						    help="Path to the pretrained TF ALIGN checkpoint.",
						)
						parser.add_argument(
						    "--pytorch_dump_folder_path",
						    default="hf_model",
						    type=str,
						    help="Path to the output PyTorch model directory.",
						)
						parser.add_argument("--save_model", action="store_true", help="Save model to local")
						parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")

						_snake_case       :      int       =					parser.parse_args()
						convert_align_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)







"""simple docstring"""



import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


_snake_case       :      Dict       =					"\\n@inproceedings{Rajpurkar2016SQuAD10,\n  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n  booktitle={EMNLP},\n  year={2016}\n}\n"

_snake_case       :      List[str]       =					"\nThis metric wrap the official scoring script for version 2 of the Stanford Question\nAnswering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n\nSQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions\nwritten adversarially by crowdworkers to look similar to answerable ones.\nTo do well on SQuAD2.0, systems must not only answer questions when possible, but also\ndetermine when no answer is supported by the paragraph and abstain from answering.\n"

_snake_case       :      Dict       =					"\nComputes SQuAD v2 scores (F1 and EM).\nArgs:\n    predictions: List of triple for question-answers to score with the following elements:\n        - the question-answer 'id' field as given in the references (see below)\n        - the text of the answer\n        - the probability that the question has no answer\n    references: List of question-answers dictionaries with the following key-values:\n            - 'id': id of the question-answer pair (see above),\n            - 'answers': a list of Dict {'text': text of the answer as a string}\n    no_answer_threshold: float\n        Probability threshold to decide that a question has no answer.\nReturns:\n    'exact': Exact match (the normalized answer exactly match the gold answer)\n    'f1': The F-score of predicted tokens versus the gold answer\n    'total': Number of score considered\n    'HasAns_exact': Exact match (the normalized answer exactly match the gold answer)\n    'HasAns_f1': The F-score of predicted tokens versus the gold answer\n    'HasAns_total': Number of score considered\n    'NoAns_exact': Exact match (the normalized answer exactly match the gold answer)\n    'NoAns_f1': The F-score of predicted tokens versus the gold answer\n    'NoAns_total': Number of score considered\n    'best_exact': Best exact match (with varying threshold)\n    'best_exact_thresh': No-answer probability threshold associated to the best exact match\n    'best_f1': Best F1 (with varying threshold)\n    'best_f1_thresh': No-answer probability threshold associated to the best F1\nExamples:\n\n    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22', 'no_answer_probability': 0.}]\n    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]\n    >>> squad_v2_metric = datasets.load_metric(\"squad_v2\")\n    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact': 100.0, 'f1': 100.0, 'total': 1, 'HasAns_exact': 100.0, 'HasAns_f1': 100.0, 'HasAns_total': 1, 'best_exact': 100.0, 'best_exact_thresh': 0.0, 'best_f1': 100.0, 'best_f1_thresh': 0.0}\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,							_KWARGS_DESCRIPTION  )
class        __lowercase(       datasets.Metric  ):






						def 		lowerCAmelCase   (					self)			->  int:




											"""simple docstring"""





											return datasets.MetricInfo(
											    description=_DESCRIPTION    ,						citation=_CITATION    ,						inputs_description=_KWARGS_DESCRIPTION    ,						features=datasets.Features(
											        {
											            'predictions': {
											                'id': datasets.Value('string'),
											                'prediction_text': datasets.Value('string'),
											                'no_answer_probability': datasets.Value('float32'),
											            },
											            'references': {
											                'id': datasets.Value('string'),
											                'answers': datasets.features.Sequence(
											                    {'text': datasets.Value('string'), 'answer_start': datasets.Value('int32')}),
											            },
											        })    ,						codebase_urls=['https://rajpurkar.github.io/SQuAD-explorer/']    ,						reference_urls=['https://rajpurkar.github.io/SQuAD-explorer/']    ,						)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=1.0)			->  Optional[int]:




											"""simple docstring"""





											lowerCamelCase__				={p['id']: p['no_answer_probability'] for p in predictions}
											lowerCamelCase__				=[{'paragraphs': [{'qas': references}]}]
											lowerCamelCase__				={p['id']: p['prediction_text'] for p in predictions}

											lowerCamelCase__				=make_qid_to_has_ans(_SCREAMING_SNAKE_CASE)  # maps qid to True/False
											lowerCamelCase__				=[k for k, v in qid_to_has_ans.items() if v]
											lowerCamelCase__				=[k for k, v in qid_to_has_ans.items() if not v]

											lowerCamelCase__				,     lowerCamelCase__				=get_raw_scores(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=apply_no_ans_threshold(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=apply_no_ans_threshold(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=make_eval_dict(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)

											if has_ans_qids:
																lowerCamelCase__				=make_eval_dict(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						qid_list=_SCREAMING_SNAKE_CASE)
																merge_eval(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						'HasAns')
											if no_ans_qids:
																lowerCamelCase__				=make_eval_dict(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						qid_list=_SCREAMING_SNAKE_CASE)
																merge_eval(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						'NoAns')
											find_all_best_thresh(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											return dict(_SCREAMING_SNAKE_CASE)