
"""simple docstring"""






import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
				from PIL import Image
else:




				class      _SCREAMING_SNAKE_CASE   :






							@staticmethod
							def 					__lowerCAmelCase					(   *__A			,  **__A			)     ->	Dict:
										pass




@is_pipeline_test
@require_torch_or_tf
@require_vision
class      _SCREAMING_SNAKE_CASE   (     unittest.TestCase				):
			UpperCAmelCase_    :Tuple												=		MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
			UpperCAmelCase_    :Any												=		TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING






			def 					__lowerCAmelCase					(   self			,  __A			,  __A			,  __A			)     ->	List[str]:
						lowerCAmelCase_       :Dict     	=    ImageClassificationPipeline(model=__A			,  image_processor=__A			,  top_k=2			)
						lowerCAmelCase_       :List[str]     	=    [
						    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			),
						    """http://images.cocodataset.org/val2017/000000039769.jpg""",
						]
						return image_classifier, examples






			def 					__lowerCAmelCase					(   self			,  __A			,  __A			)     ->	Tuple:
						lowerCAmelCase_       :int     	=    image_classifier("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)

						self.assertEqual(
						    __A			,  [
						        {"""score""": ANY(__A			), """label""": ANY(__A			)},
						        {"""score""": ANY(__A			), """label""": ANY(__A			)},
						    ]			,  )

						import datasets

						lowerCAmelCase_       :Optional[Any]     	=    datasets.load_dataset("""hf-internal-testing/fixtures_image_utils"""			,  """image"""			,  split="""test"""			)

						# Accepts URL + PIL.Image + lists
						lowerCAmelCase_       :Union[str, Any]     	=    image_classifier(
						    [
						        Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			),
						        """http://images.cocodataset.org/val2017/000000039769.jpg""",
						        # RGBA
						        dataset[0]["""file"""],
						        # LA
						        dataset[1]["""file"""],
						        # L
						        dataset[2]["""file"""],
						    ]			)
						self.assertEqual(
						    __A			,  [
						        [
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						        ],
						        [
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						        ],
						        [
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						        ],
						        [
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						        ],
						        [
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						            {"""score""": ANY(__A			), """label""": ANY(__A			)},
						        ],
						    ]			,  )






			@require_torch
			def 					__lowerCAmelCase					(   self			)     ->	List[Any]:
						lowerCAmelCase_       :Dict     	=    """hf-internal-testing/tiny-random-vit"""
						lowerCAmelCase_       :str     	=    pipeline("""image-classification"""			,  model=__A			)

						lowerCAmelCase_       :str     	=    image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""			)
						self.assertEqual(
						    nested_simplify(__A			,  decimals=4			)			,  [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}]			,  )

						lowerCAmelCase_       :str     	=    image_classifier(
						    [
						        """http://images.cocodataset.org/val2017/000000039769.jpg""",
						        """http://images.cocodataset.org/val2017/000000039769.jpg""",
						    ]			,  top_k=2			,  )
						self.assertEqual(
						    nested_simplify(__A			,  decimals=4			)			,  [
						        [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
						        [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
						    ]			,  )






			@require_tf
			def 					__lowerCAmelCase					(   self			)     ->	str:
						lowerCAmelCase_       :Dict     	=    """hf-internal-testing/tiny-random-vit"""
						lowerCAmelCase_       :Any     	=    pipeline("""image-classification"""			,  model=__A			,  framework="""tf"""			)

						lowerCAmelCase_       :List[str]     	=    image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""			)
						self.assertEqual(
						    nested_simplify(__A			,  decimals=4			)			,  [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}]			,  )

						lowerCAmelCase_       :Optional[int]     	=    image_classifier(
						    [
						        """http://images.cocodataset.org/val2017/000000039769.jpg""",
						        """http://images.cocodataset.org/val2017/000000039769.jpg""",
						    ]			,  top_k=2			,  )
						self.assertEqual(
						    nested_simplify(__A			,  decimals=4			)			,  [
						        [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
						        [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
						    ]			,  )






			def 					__lowerCAmelCase					(   self			)     ->	Optional[Any]:
						lowerCAmelCase_       :Dict     	=    PreTrainedTokenizer()

						# Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
						lowerCAmelCase_       :Dict     	=    pipeline(
						    """image-classification"""			,  model="""hf-internal-testing/tiny-random-vit"""			,  tokenizer=__A			)

						self.assertIs(image_classifier.tokenizer			,  __A			)






			@slow
			@require_torch
			def 					__lowerCAmelCase					(   self			)     ->	int:
						# Perceiver is not tested by `run_pipeline_test` properly.
						# That is because the type of feature_extractor and model preprocessor need to be kept
						# in sync, which is not the case in the current design
						lowerCAmelCase_       :int     	=    pipeline("""image-classification"""			,  model="""deepmind/vision-perceiver-conv"""			)
						lowerCAmelCase_       :Tuple     	=    image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""			)
						self.assertEqual(
						    nested_simplify(__A			,  decimals=4			)			,  [
						        {"""score""": 0.4_3_8_5, """label""": """tabby, tabby cat"""},
						        {"""score""": 0.3_2_1, """label""": """tiger cat"""},
						        {"""score""": 0.0_5_0_2, """label""": """Egyptian cat"""},
						        {"""score""": 0.0_1_3_7, """label""": """crib, cot"""},
						        {"""score""": 0.0_0_7, """label""": """radiator"""},
						    ]			,  )

						lowerCAmelCase_       :str     	=    pipeline("""image-classification"""			,  model="""deepmind/vision-perceiver-fourier"""			)
						lowerCAmelCase_       :Tuple     	=    image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""			)
						self.assertEqual(
						    nested_simplify(__A			,  decimals=4			)			,  [
						        {"""score""": 0.5_6_5_8, """label""": """tabby, tabby cat"""},
						        {"""score""": 0.1_3_0_9, """label""": """tiger cat"""},
						        {"""score""": 0.0_7_2_2, """label""": """Egyptian cat"""},
						        {"""score""": 0.0_7_0_7, """label""": """remote control, remote"""},
						        {"""score""": 0.0_0_8_2, """label""": """computer keyboard, keypad"""},
						    ]			,  )

						lowerCAmelCase_       :Any     	=    pipeline("""image-classification"""			,  model="""deepmind/vision-perceiver-learned"""			)
						lowerCAmelCase_       :List[str]     	=    image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""			)
						self.assertEqual(
						    nested_simplify(__A			,  decimals=4			)			,  [
						        {"""score""": 0.3_0_2_2, """label""": """tabby, tabby cat"""},
						        {"""score""": 0.2_3_6_2, """label""": """Egyptian cat"""},
						        {"""score""": 0.1_8_5_6, """label""": """tiger cat"""},
						        {"""score""": 0.0_3_2_4, """label""": """remote control, remote"""},
						        {"""score""": 0.0_0_9_6, """label""": """quilt, comforter, comfort, puff"""},
						    ]			,  )








"""simple docstring"""






from ...configuration_utils import PretrainedConfig
from ...utils import is_detectrona_available, logging


__UpperCAmelCase 					=    logging.get_logger(__name__)

__UpperCAmelCase 					=    {
    'layoutlmv2-base-uncased': 'https://huggingface.co/microsoft/layoutlmv2-base-uncased/resolve/main/config.json',
    'layoutlmv2-large-uncased': 'https://huggingface.co/microsoft/layoutlmv2-large-uncased/resolve/main/config.json',
    # See all LayoutLMv2 models at https://huggingface.co/models?filter=layoutlmv2
}

# soft dependency
if is_detectrona_available():
				import detectrona




class      _SCREAMING_SNAKE_CASE   (     A__				):
			UpperCAmelCase_    :Optional[int]												=		"layoutlmv2"






			def __init__(   self			,  __A=3_0522			,  __A=768			,  __A=12			,  __A=12			,  __A=3072			,  __A="gelu"			,  __A=0.1			,  __A=0.1			,  __A=512			,  __A=2			,  __A=0.0_2			,  __A=1E-12			,  __A=0			,  __A=1024			,  __A=128			,  __A=32			,  __A=True			,  __A=256			,  __A=64			,  __A=True			,  __A=[7, 7, 256]			,  __A=128			,  __A=128			,  __A=True			,  __A=True			,  __A=False			,  __A=None			,  **__A			,  )     ->	List[str]:
						super().__init__(
						    vocab_size=__A			,  hidden_size=__A			,  num_hidden_layers=__A			,  num_attention_heads=__A			,  intermediate_size=__A			,  hidden_act=__A			,  hidden_dropout_prob=__A			,  attention_probs_dropout_prob=__A			,  max_position_embeddings=__A			,  type_vocab_size=__A			,  initializer_range=__A			,  layer_norm_eps=__A			,  pad_token_id=__A			,  **__A			,  )
						lowerCAmelCase_       :Optional[Any]     	=    max_ad_position_embeddings
						lowerCAmelCase_       :Dict     	=    max_rel_pos
						lowerCAmelCase_       :str     	=    rel_pos_bins
						lowerCAmelCase_       :List[str]     	=    fast_qkv
						lowerCAmelCase_       :Union[str, Any]     	=    max_rel_ad_pos
						lowerCAmelCase_       :List[str]     	=    rel_ad_pos_bins
						lowerCAmelCase_       :Any     	=    convert_sync_batchnorm
						lowerCAmelCase_       :Dict     	=    image_feature_pool_shape
						lowerCAmelCase_       :str     	=    coordinate_size
						lowerCAmelCase_       :Tuple     	=    shape_size
						lowerCAmelCase_       :Tuple     	=    has_relative_attention_bias
						lowerCAmelCase_       :Union[str, Any]     	=    has_spatial_attention_bias
						lowerCAmelCase_       :int     	=    has_visual_segment_embedding
						lowerCAmelCase_       :Any     	=    (
						    detectrona_config_args if detectrona_config_args is not None else self.get_default_detectrona_config()
						)






			@classmethod
			def 					__lowerCAmelCase					(   self			)     ->	Optional[Any]:
						return {
						    "MODEL.MASK_ON": True,
						    "MODEL.PIXEL_STD": [5_7.3_7_5, 5_7.1_2_0, 5_8.3_9_5],
						    "MODEL.BACKBONE.NAME": "build_resnet_fpn_backbone",
						    "MODEL.FPN.IN_FEATURES": ["res2", "res3", "res4", "res5"],
						    "MODEL.ANCHOR_GENERATOR.SIZES": [[32], [64], [128], [256], [512]],
						    "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
						    "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 2000,
						    "MODEL.RPN.PRE_NMS_TOPK_TEST": 1000,
						    "MODEL.RPN.POST_NMS_TOPK_TRAIN": 1000,
						    "MODEL.POST_NMS_TOPK_TEST": 1000,
						    "MODEL.ROI_HEADS.NAME": "StandardROIHeads",
						    "MODEL.ROI_HEADS.NUM_CLASSES": 5,
						    "MODEL.ROI_HEADS.IN_FEATURES": ["p2", "p3", "p4", "p5"],
						    "MODEL.ROI_BOX_HEAD.NAME": "FastRCNNConvFCHead",
						    "MODEL.ROI_BOX_HEAD.NUM_FC": 2,
						    "MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION": 14,
						    "MODEL.ROI_MASK_HEAD.NAME": "MaskRCNNConvUpsampleHead",
						    "MODEL.ROI_MASK_HEAD.NUM_CONV": 4,
						    "MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION": 7,
						    "MODEL.RESNETS.DEPTH": 101,
						    "MODEL.RESNETS.SIZES": [[32], [64], [128], [256], [512]],
						    "MODEL.RESNETS.ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
						    "MODEL.RESNETS.OUT_FEATURES": ["res2", "res3", "res4", "res5"],
						    "MODEL.RESNETS.NUM_GROUPS": 32,
						    "MODEL.RESNETS.WIDTH_PER_GROUP": 8,
						    "MODEL.RESNETS.STRIDE_IN_1X1": False,
						}






			def 					__lowerCAmelCase					(   self			)     ->	List[Any]:
						lowerCAmelCase_       :Any     	=    detectrona.config.get_cfg()
						for k, v in self.detectrona_config_args.items():
									lowerCAmelCase_       :int     	=    k.split("""."""			)
									lowerCAmelCase_       :List[Any]     	=    detectrona_config
									for attribute in attributes[:-1]:
												lowerCAmelCase_       :List[Any]     	=    getattr(__A			,  __A			)
									setattr(__A			,  attributes[-1]			,  __A			)

						return detectrona_config






