import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import (
		    FocalNetBackbone,
		    FocalNetForImageClassification,
		    FocalNetForMaskedImageModeling,
		    FocalNetModel,
		)
		from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor



class   lowerCamelCase				:







		'''simple docstring'''



		def __init__(							self    ,		_UpperCamelCase    ,		_UpperCamelCase=1_3    ,		_UpperCamelCase=3_2    ,		_UpperCamelCase=2    ,		_UpperCamelCase=3    ,		_UpperCamelCase=1_6    ,		_UpperCamelCase=[3_2, 6_4, 1_2_8]    ,		_UpperCamelCase=[1, 2, 1]    ,		_UpperCamelCase=[2, 2, 4]    ,		_UpperCamelCase=2    ,		_UpperCamelCase=2.0    ,		_UpperCamelCase=True    ,		_UpperCamelCase=0.0    ,		_UpperCamelCase=0.0    ,		_UpperCamelCase=0.1    ,		_UpperCamelCase="gelu"    ,		_UpperCamelCase=False    ,		_UpperCamelCase=True    ,		_UpperCamelCase=0.02    ,		_UpperCamelCase=1E-5    ,		_UpperCamelCase=True    ,		_UpperCamelCase=None    ,		_UpperCamelCase=True    ,		_UpperCamelCase=1_0    ,		_UpperCamelCase=8    ,		_UpperCamelCase=["stage1", "stage2"]    ,		_UpperCamelCase=[1, 2]    ,		)     ->							Union[str, Any]:
							UpperCAmelCase_   :				Optional[int]						=						parent
							UpperCAmelCase_   :				Tuple						=						batch_size
							UpperCAmelCase_   :				Dict						=						image_size
							UpperCAmelCase_   :				Optional[int]						=						patch_size
							UpperCAmelCase_   :				int						=						num_channels
							UpperCAmelCase_   :				Dict						=						embed_dim
							UpperCAmelCase_   :				Dict						=						hidden_sizes
							UpperCAmelCase_   :				Optional[int]						=						depths
							UpperCAmelCase_   :				Optional[int]						=						num_heads
							UpperCAmelCase_   :				Optional[Any]						=						window_size
							UpperCAmelCase_   :				Optional[Any]						=						mlp_ratio
							UpperCAmelCase_   :				Union[str, Any]						=						qkv_bias
							UpperCAmelCase_   :				Union[str, Any]						=						hidden_dropout_prob
							UpperCAmelCase_   :				str						=						attention_probs_dropout_prob
							UpperCAmelCase_   :				Optional[Any]						=						drop_path_rate
							UpperCAmelCase_   :				str						=						hidden_act
							UpperCAmelCase_   :				Optional[Any]						=						use_absolute_embeddings
							UpperCAmelCase_   :				Tuple						=						patch_norm
							UpperCAmelCase_   :				int						=						layer_norm_eps
							UpperCAmelCase_   :				int						=						initializer_range
							UpperCAmelCase_   :				Optional[int]						=						is_training
							UpperCAmelCase_   :				Tuple						=						scope
							UpperCAmelCase_   :				Dict						=						use_labels
							UpperCAmelCase_   :				Union[str, Any]						=						type_sequence_label_size
							UpperCAmelCase_   :				int						=						encoder_stride
							UpperCAmelCase_   :				Optional[Any]						=						out_features
							UpperCAmelCase_   :				Optional[Any]						=						out_indices



		def  __UpperCAmelCase      (							self       )     ->							str:
							UpperCAmelCase_   :				Union[str, Any]						=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

							UpperCAmelCase_   :				List[Any]						=						None
							if self.use_labels:
												UpperCAmelCase_   :				str						=						ids_tensor([self.batch_size]    ,		self.type_sequence_label_size       )

							UpperCAmelCase_   :				Tuple						=						self.get_config()

							return config, pixel_values, labels



		def  __UpperCAmelCase      (							self       )     ->							Dict:
							return FocalNetConfig(
							    image_size=self.image_size    ,		patch_size=self.patch_size    ,		num_channels=self.num_channels    ,		embed_dim=self.embed_dim    ,		hidden_sizes=self.hidden_sizes    ,		depths=self.depths    ,		num_heads=self.num_heads    ,		window_size=self.window_size    ,		mlp_ratio=self.mlp_ratio    ,		qkv_bias=self.qkv_bias    ,		hidden_dropout_prob=self.hidden_dropout_prob    ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,		drop_path_rate=self.drop_path_rate    ,		hidden_act=self.hidden_act    ,		use_absolute_embeddings=self.use_absolute_embeddings    ,		path_norm=self.patch_norm    ,		layer_norm_eps=self.layer_norm_eps    ,		initializer_range=self.initializer_range    ,		encoder_stride=self.encoder_stride    ,		out_features=self.out_features    ,		out_indices=self.out_indices    ,		)



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase       )     ->							Dict:
							UpperCAmelCase_   :				Tuple						=						FocalNetModel(config=UpperCamelCase__       )
							model.to(UpperCamelCase__       )
							model.eval()
							UpperCAmelCase_   :				Union[str, Any]						=						model(UpperCamelCase__       )

							UpperCAmelCase_   :				List[str]						=						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths       ) - 1))
							UpperCAmelCase_   :				Any						=						int(config.embed_dim * 2 ** (len(config.depths       ) - 1)       )

							self.parent.assertEqual(result.last_hidden_state.shape    ,		(self.batch_size, expected_seq_len, expected_dim)       )



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase       )     ->							Dict:
							UpperCAmelCase_   :				str						=						FocalNetBackbone(config=UpperCamelCase__       )
							model.to(UpperCamelCase__       )
							model.eval()
							UpperCAmelCase_   :				Union[str, Any]						=						model(UpperCamelCase__       )

							# verify feature maps
							self.parent.assertEqual(len(result.feature_maps       )    ,		len(config.out_features       )       )
							self.parent.assertListEqual(list(result.feature_maps[0].shape       )    ,		[self.batch_size, self.image_size, 8, 8]       )

							# verify channels
							self.parent.assertEqual(len(model.channels       )    ,		len(config.out_features       )       )
							self.parent.assertListEqual(model.channels    ,		config.hidden_sizes[:-1]       )

							# verify backbone works with out_features=None
							UpperCAmelCase_   :				Optional[Any]						=						None
							UpperCAmelCase_   :				Dict						=						FocalNetBackbone(config=UpperCamelCase__       )
							model.to(UpperCamelCase__       )
							model.eval()
							UpperCAmelCase_   :				Optional[Any]						=						model(UpperCamelCase__       )

							# verify feature maps
							self.parent.assertEqual(len(result.feature_maps       )    ,		1       )
							self.parent.assertListEqual(list(result.feature_maps[0].shape       )    ,		[self.batch_size, self.image_size * 2, 4, 4]       )

							# verify channels
							self.parent.assertEqual(len(model.channels       )    ,		1       )
							self.parent.assertListEqual(model.channels    ,		[config.hidden_sizes[-1]]       )



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase       )     ->							int:
							UpperCAmelCase_   :				Optional[Any]						=						FocalNetForMaskedImageModeling(config=UpperCamelCase__       )
							model.to(UpperCamelCase__       )
							model.eval()
							UpperCAmelCase_   :				str						=						model(UpperCamelCase__       )
							self.parent.assertEqual(
							    result.reconstruction.shape    ,		(self.batch_size, self.num_channels, self.image_size, self.image_size)       )

							# test greyscale images
							UpperCAmelCase_   :				Optional[Any]						=						1
							UpperCAmelCase_   :				Dict						=						FocalNetForMaskedImageModeling(UpperCamelCase__       )
							model.to(UpperCamelCase__       )
							model.eval()

							UpperCAmelCase_   :				Union[str, Any]						=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
							UpperCAmelCase_   :				Optional[Any]						=						model(UpperCamelCase__       )
							self.parent.assertEqual(result.reconstruction.shape    ,		(self.batch_size, 1, self.image_size, self.image_size)       )



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase       )     ->							Any:
							UpperCAmelCase_   :				Union[str, Any]						=						self.type_sequence_label_size
							UpperCAmelCase_   :				List[Any]						=						FocalNetForImageClassification(UpperCamelCase__       )
							model.to(UpperCamelCase__       )
							model.eval()
							UpperCAmelCase_   :				Tuple						=						model(UpperCamelCase__    ,		labels=UpperCamelCase__       )
							self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.type_sequence_label_size)       )

							# test greyscale images
							UpperCAmelCase_   :				int						=						1
							UpperCAmelCase_   :				Tuple						=						FocalNetForImageClassification(UpperCamelCase__       )
							model.to(UpperCamelCase__       )
							model.eval()

							UpperCAmelCase_   :				Any						=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
							UpperCAmelCase_   :				Tuple						=						model(UpperCamelCase__       )
							self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.type_sequence_label_size)       )



		def  __UpperCAmelCase      (							self       )     ->							Optional[int]:
							UpperCAmelCase_   :				List[str]						=						self.prepare_config_and_inputs()

							UpperCAmelCase_	,  UpperCAmelCase_	,  UpperCAmelCase_   :				int						=						config_and_inputs
							UpperCAmelCase_   :				int						=						{'pixel_values': pixel_values}
							return config, inputs_dict





@require_torch
class   lowerCamelCase				(__a			,  __a			,  unittest.TestCase      ):







		'''simple docstring'''



		_snake_case   :   Optional[int]							=  (
		    (
		        FocalNetModel,
		        FocalNetForImageClassification,
		        FocalNetForMaskedImageModeling,
		        FocalNetBackbone,
		    )
		    if is_torch_available()
		    else ()
		)
		_snake_case   :   Union[str, Any]							=  (
		    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
		    if is_torch_available()
		    else {}
		)
		_snake_case   :   Tuple							=  False

		_snake_case   :   List[str]							=  False
		_snake_case   :   List[Any]							=  False
		_snake_case   :   int							=  False
		_snake_case   :   Optional[Any]							=  False



		def  __UpperCAmelCase      (							self       )     ->							List[str]:
							UpperCAmelCase_   :				Dict						=						FocalNetModelTester(self       )
							UpperCAmelCase_   :				str						=						ConfigTester(self    ,		config_class=UpperCamelCase__    ,		embed_dim=3_7    ,		has_text_modality=UpperCamelCase__       )



		def  __UpperCAmelCase      (							self       )     ->							Optional[int]:
							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()



		def  __UpperCAmelCase      (							self       )     ->							int:
							return



		def  __UpperCAmelCase      (							self       )     ->							Optional[int]:
							UpperCAmelCase_   :				int						=						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCamelCase__       )



		def  __UpperCAmelCase      (							self       )     ->							Any:
							UpperCAmelCase_   :				Dict						=						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*UpperCamelCase__       )



		def  __UpperCAmelCase      (							self       )     ->							Optional[Any]:
							UpperCAmelCase_   :				List[Any]						=						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__       )



		def  __UpperCAmelCase      (							self       )     ->							List[str]:
							UpperCAmelCase_   :				Dict						=						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__       )



		@unittest.skip(reason='FocalNet does not use inputs_embeds'       )
		def  __UpperCAmelCase      (							self       )     ->							List[Any]:
							pass



		@unittest.skip(reason='FocalNet does not use feedforward chunking'       )
		def  __UpperCAmelCase      (							self       )     ->							Any:
							pass



		def  __UpperCAmelCase      (							self       )     ->							Union[str, Any]:
							UpperCAmelCase_	,  UpperCAmelCase_   :				Any						=						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes[:-1]:
												UpperCAmelCase_   :				int						=						model_class(UpperCamelCase__       )
												self.assertIsInstance(model.get_input_embeddings()    ,		(nn.Module)       )
												UpperCAmelCase_   :				List[str]						=						model.get_output_embeddings()
												self.assertTrue(x is None or isinstance(UpperCamelCase__    ,		nn.Linear       )       )



		def  __UpperCAmelCase      (							self       )     ->							Tuple:
							UpperCAmelCase_	,  UpperCAmelCase_   :				str						=						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes[:-1]:
												UpperCAmelCase_   :				str						=						model_class(UpperCamelCase__       )
												UpperCAmelCase_   :				Any						=						inspect.signature(model.forward       )
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												UpperCAmelCase_   :				Tuple						=						[*signature.parameters.keys()]

												UpperCAmelCase_   :				Tuple						=						['pixel_values']
												self.assertListEqual(arg_names[:1]    ,		UpperCamelCase__       )



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase       )     ->							Dict:
							UpperCAmelCase_   :				Union[str, Any]						=						model_class(UpperCamelCase__       )
							model.to(UpperCamelCase__       )
							model.eval()

							with torch.no_grad():
												UpperCAmelCase_   :				Optional[int]						=						model(**self._prepare_for_class(UpperCamelCase__    ,		UpperCamelCase__       )       )

							UpperCAmelCase_   :				Any						=						outputs.hidden_states

							UpperCAmelCase_   :				str						=						getattr(
							    self.model_tester    ,		'expected_num_hidden_layers'    ,		len(self.model_tester.depths       ) + 1       )
							self.assertEqual(len(UpperCamelCase__       )    ,		UpperCamelCase__       )

							# FocalNet has a different seq_length
							UpperCAmelCase_   :				int						=						(
							    config.patch_size
							    if isinstance(config.patch_size    ,		collections.abc.Iterable       )
							    else (config.patch_size, config.patch_size)
							)

							UpperCAmelCase_   :				Union[str, Any]						=						(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

							self.assertListEqual(
							    list(hidden_states[0].shape[-2:]       )    ,		[num_patches, self.model_tester.embed_dim]    ,		)

							UpperCAmelCase_   :				int						=						outputs.reshaped_hidden_states
							self.assertEqual(len(UpperCamelCase__       )    ,		UpperCamelCase__       )

							UpperCAmelCase_	,  UpperCAmelCase_	,  UpperCAmelCase_	,  UpperCAmelCase_   :				Union[str, Any]						=						reshaped_hidden_states[0].shape
							UpperCAmelCase_   :				List[Any]						=						(
							    reshaped_hidden_states[0].view(UpperCamelCase__    ,		UpperCamelCase__    ,		height * width       ).permute(0    ,		2    ,		1       )
							)
							self.assertListEqual(
							    list(reshaped_hidden_states.shape[-2:]       )    ,		[num_patches, self.model_tester.embed_dim]    ,		)



		def  __UpperCAmelCase      (							self       )     ->							int:
							UpperCAmelCase_	,  UpperCAmelCase_   :				int						=						self.model_tester.prepare_config_and_inputs_for_common()

							UpperCAmelCase_   :				Optional[Any]						=						(
							    self.model_tester.image_size
							    if isinstance(self.model_tester.image_size    ,		collections.abc.Iterable       )
							    else (self.model_tester.image_size, self.model_tester.image_size)
							)

							for model_class in self.all_model_classes[:-1]:
												UpperCAmelCase_   :				Optional[int]						=						True
												self.check_hidden_states_output(UpperCamelCase__    ,		UpperCamelCase__    ,		UpperCamelCase__    ,		UpperCamelCase__       )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												UpperCAmelCase_   :				Optional[int]						=						True

												self.check_hidden_states_output(UpperCamelCase__    ,		UpperCamelCase__    ,		UpperCamelCase__    ,		UpperCamelCase__       )



		def  __UpperCAmelCase      (							self       )     ->							Union[str, Any]:
							UpperCAmelCase_	,  UpperCAmelCase_   :				Union[str, Any]						=						self.model_tester.prepare_config_and_inputs_for_common()
							UpperCAmelCase_   :				Optional[int]						=						3

							UpperCAmelCase_   :				Tuple						=						(
							    self.model_tester.image_size
							    if isinstance(self.model_tester.image_size    ,		collections.abc.Iterable       )
							    else (self.model_tester.image_size, self.model_tester.image_size)
							)
							UpperCAmelCase_   :				Union[str, Any]						=						(
							    config.patch_size
							    if isinstance(config.patch_size    ,		collections.abc.Iterable       )
							    else (config.patch_size, config.patch_size)
							)

							UpperCAmelCase_   :				List[str]						=						image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
							UpperCAmelCase_   :				Optional[int]						=						image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

							for model_class in self.all_model_classes[:-1]:
												UpperCAmelCase_   :				str						=						True
												self.check_hidden_states_output(UpperCamelCase__    ,		UpperCamelCase__    ,		UpperCamelCase__    ,		(padded_height, padded_width)       )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												UpperCAmelCase_   :				List[str]						=						True
												self.check_hidden_states_output(UpperCamelCase__    ,		UpperCamelCase__    ,		UpperCamelCase__    ,		(padded_height, padded_width)       )



		@slow
		def  __UpperCAmelCase      (							self       )     ->							List[Any]:



							for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase_   :				Optional[int]						=						FocalNetModel.from_pretrained(UpperCamelCase__       )
												self.assertIsNotNone(UpperCamelCase__       )



		def  __UpperCAmelCase      (							self       )     ->							Any:
							UpperCAmelCase_	,  UpperCAmelCase_   :				Union[str, Any]						=						self.model_tester.prepare_config_and_inputs_for_common()

							UpperCAmelCase_   :				List[str]						=						_config_zero_init(UpperCamelCase__       )
							for model_class in self.all_model_classes:
												UpperCAmelCase_   :				Tuple						=						model_class(config=UpperCamelCase__       )
												for name, param in model.named_parameters():
																	if "embeddings" not in name and param.requires_grad:
																						self.assertIn(
																						    ((param.data.mean() * 1E9).round() / 1E9).item()    ,		[0.0, 1.0]    ,		msg=f"Parameter {name} of model {model_class} seems not properly initialized"    ,		)





@require_vision
@require_torch
class   lowerCamelCase				(unittest.TestCase      ):







		'''simple docstring'''



		@cached_property
		def  __UpperCAmelCase      (							self       )     ->							Dict:
							return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'       ) if is_vision_available() else None



		@slow
		def  __UpperCAmelCase      (							self       )     ->							str:
							UpperCAmelCase_   :				List[str]						=						FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'       ).to(UpperCamelCase__       )
							UpperCAmelCase_   :				str						=						self.default_image_processor

							UpperCAmelCase_   :				Any						=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
							UpperCAmelCase_   :				int						=						image_processor(images=UpperCamelCase__    ,		return_tensors='pt'       ).to(UpperCamelCase__       )

							# forward pass
							with torch.no_grad():
												UpperCAmelCase_   :				Optional[Any]						=						model(**UpperCamelCase__       )

							# verify the logits
							UpperCAmelCase_   :				Dict						=						torch.Size((1, 1_0_0_0)       )
							self.assertEqual(outputs.logits.shape    ,		UpperCamelCase__       )
							UpperCAmelCase_   :				List[Any]						=						torch.tensor([0.21_66, -0.43_68, 0.21_91]       ).to(UpperCamelCase__       )
							self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,		UpperCamelCase__    ,		atol=1E-4       )       )
							self.assertTrue(outputs.logits.argmax(dim=-1       ).item()    ,		2_8_1       )





@require_torch
class   lowerCamelCase				(__a			,  unittest.TestCase      ):







		'''simple docstring'''



		_snake_case   :   str							=  (FocalNetBackbone,) if is_torch_available() else ()
		_snake_case   :   List[Any]							=  FocalNetConfig

		_snake_case   :   List[str]							=  False



		def  __UpperCAmelCase      (							self       )     ->							Dict:
							UpperCAmelCase_   :				List[str]						=						FocalNetModelTester(self       )














import argparse
import json
import os

from tensorflow.core.protobuf.saved_model_pba import SavedModel


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_copies.py
__UpperCAmelCase     							=						'.'

# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model)
__UpperCAmelCase     							=						[
    'Assert',
    'AssignVariableOp',
    'EmptyTensorList',
    'MergeV2Checkpoints',
    'ReadVariableOp',
    'ResourceGather',
    'RestoreV2',
    'SaveV2',
    'ShardedFilename',
    'StatefulPartitionedCall',
    'StaticRegexFullMatch',
    'VarHandleOp',
]




def 					lowercase__				(					__snake_case   :							Union[str, Any]					,	__snake_case   :							Optional[int]					,	__snake_case   :							Union[str, Any]  ):


					'''simple docstring'''


					UpperCAmelCase_   :				Optional[Any]						=						SavedModel()
					UpperCAmelCase_   :				Optional[Any]						=						[]

					with open(os.path.join(__snake_case					,	'utils'					,	'tf_ops'					,	'onnx.json'  )  ) as f:
										UpperCAmelCase_   :				Optional[Any]						=						json.load(__snake_case  )['opsets']

					for i in range(1					,	opset + 1  ):
										onnx_ops.extend(onnx_opsets[str(__snake_case  )]  )

					with open(__snake_case					,	'rb'  ) as f:
										saved_model.ParseFromString(f.read()  )

					UpperCAmelCase_   :				List[Any]						=						set()

					# Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs)
					for meta_graph in saved_model.meta_graphs:
										# Add operations in the graph definition
										model_op_names.update(node.op for node in meta_graph.graph_def.node  )

										# Go through the functions in the graph definition
										for func in meta_graph.graph_def.library.function:
															# Add operations in each function
															model_op_names.update(node.op for node in func.node_def  )

    # Convert to list, sorted if you want
					UpperCAmelCase_   :				Optional[int]						=						sorted(__snake_case  )
					UpperCAmelCase_   :				int						=						[]

					for op in model_op_names:
										if op not in onnx_ops and op not in INTERNAL_OPS:
															incompatible_ops.append(__snake_case  )

					if strict and len(__snake_case  ) > 0:
										raise Exception(F"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops  )
					elif len(__snake_case  ) > 0:
										print(F"Found the following incompatible ops for the opset {opset}:"  )
										print(*__snake_case					,	sep='\n'  )
					else:
										print(F"The saved model {saved_model_path} can properly be converted with ONNX."  )


if __name__ == "__main__":
		__UpperCAmelCase     							=						argparse.ArgumentParser()
		parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).')
		parser.add_argument(
		    '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.'
		)
		parser.add_argument(
		    '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.'
		)
		parser.add_argument(
		    '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)'
		)
		__UpperCAmelCase     							=						parser.parse_args()

		if args.framework == "onnx":
				onnx_compliancy(args.saved_model_path, args.strict, args.opset)






