




import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel

					if is_vision_available():
										from transformers import MaskFormerImageProcessor

if is_vision_available():
					from PIL import Image
class       a__   :






						def __init__(       self		,      _A		,      _A=2		,      _A=True		,      _A=False		,      _A=1_0		,      _A=3		,      _A=3_2 * 4		,      _A=3_2 * 6		,      _A=4		,      _A=3_2		,      ):




											"""simple docstring"""



											__lowerCAmelCase           =	parent
											__lowerCAmelCase           =	batch_size
											__lowerCAmelCase           =	is_training
											__lowerCAmelCase           =	use_auxiliary_loss
											__lowerCAmelCase           =	num_queries
											__lowerCAmelCase           =	num_channels
											__lowerCAmelCase           =	min_size
											__lowerCAmelCase           =	max_size
											__lowerCAmelCase           =	num_labels
											__lowerCAmelCase           =	mask_feature_size






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]      ).to(
											    _A      )

											__lowerCAmelCase           =	torch.ones([self.batch_size, self.min_size, self.max_size]		,      device=_A      )

											__lowerCAmelCase           =	(
											    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]		,      device=_A      ) > 0.5
											).float()
											__lowerCAmelCase           =	(torch.rand((self.batch_size, self.num_labels)		,      device=_A      ) > 0.5).long()

											__lowerCAmelCase           =	self.get_config()
											return config, pixel_values, pixel_mask, mask_labels, class_labels






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											return MaskFormerConfig.from_backbone_and_decoder_configs(
											    backbone_config=SwinConfig(
											        depths=[1, 1, 1, 1]		,      )		,      decoder_config=DetrConfig(
											        decoder_ffn_dim=1_2_8		,      num_queries=self.num_queries		,      decoder_attention_heads=2		,      d_model=self.mask_feature_size		,      )		,      mask_feature_size=self.mask_feature_size		,      fpn_feature_size=self.mask_feature_size		,      num_channels=self.num_channels		,      num_labels=self.num_labels		,      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase           =	self.prepare_config_and_inputs()
											__lowerCAmelCase           =	{"pixel_values": pixel_values, "pixel_mask": pixel_mask}
											return config, inputs_dict






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A      ):




											"""simple docstring"""



											__lowerCAmelCase           =	output.encoder_hidden_states
											__lowerCAmelCase           =	output.pixel_decoder_hidden_states
											__lowerCAmelCase           =	output.transformer_decoder_hidden_states

											self.parent.assertTrue(len(_A      )		,      len(config.backbone_config.depths      )      )
											self.parent.assertTrue(len(_A      )		,      len(config.backbone_config.depths      )      )
											self.parent.assertTrue(len(_A      )		,      config.decoder_config.decoder_layers      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A		,      _A=False      ):




											"""simple docstring"""



											with torch.no_grad():
																__lowerCAmelCase           =	MaskFormerModel(config=_A      )
																model.to(_A      )
																model.eval()

																__lowerCAmelCase           =	model(pixel_values=_A		,      pixel_mask=_A      )
																__lowerCAmelCase           =	model(_A		,      output_hidden_states=_A      )
											# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
											# encoder and pixel decoder
											self.parent.assertEqual(
											    output.transformer_decoder_last_hidden_state.shape		,      (self.batch_size, self.num_queries, self.mask_feature_size)		,      )
											# let's ensure the other two hidden state exists
											self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None      )
											self.parent.assertTrue(output.encoder_last_hidden_state is not None      )

											if output_hidden_states:
																self.check_output_hidden_state(_A		,      _A      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A		,      _A		,      _A      ):




											"""simple docstring"""



											__lowerCAmelCase           =	MaskFormerForInstanceSegmentation(config=_A      )
											model.to(_A      )
											model.eval()

											def comm_check_on_output(_A      ):
																# let's still check that all the required stuff is there
																self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None      )
																self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None      )
																self.parent.assertTrue(result.encoder_last_hidden_state is not None      )
																# okay, now we need to check the logits shape
																# due to the encoder compression, masks have a //4 spatial size
																self.parent.assertEqual(
																    result.masks_queries_logits.shape		,      (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)		,      )
																# + 1 for null class
																self.parent.assertEqual(
																    result.class_queries_logits.shape		,      (self.batch_size, self.num_queries, self.num_labels + 1)      )

											with torch.no_grad():
																__lowerCAmelCase           =	model(pixel_values=_A		,      pixel_mask=_A      )
																__lowerCAmelCase           =	model(_A      )

																comm_check_on_output(_A      )

																__lowerCAmelCase           =	model(
																    pixel_values=_A		,      pixel_mask=_A		,      mask_labels=_A		,      class_labels=_A      )

											comm_check_on_output(_A      )

											self.parent.assertTrue(result.loss is not None      )
											self.parent.assertEqual(result.loss.shape		,      torch.Size([1]      )      )






@require_torch
class       a__   ( snake_case__			,    snake_case__			,    unittest.TestCase				):
						_a							:   List[str] =   (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
						_a							:   str =   (
						    {"""feature-extraction""": MaskFormerModel, """image-segmentation""": MaskFormerForInstanceSegmentation}
						    if is_torch_available()
						    else {}
						)

						_a							:   int =   False
						_a							:   str =   False
						_a							:   Optional[int] =   False
						_a							:   Optional[int] =   False






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	MaskFormerModelTester(self      )
											__lowerCAmelCase           =	ConfigTester(self		,      config_class=_A		,      has_text_modality=_A      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											self.config_tester.run_common_tests()






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase       ,							__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.create_and_check_maskformer_model(_A		,      **_A		,      output_hidden_states=_A      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_A      )






						@unittest.skip(reason="MaskFormer does not use inputs_embeds"      )
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											pass






						@unittest.skip(reason="MaskFormer does not have a get_input_embeddings method"      )
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											pass






						@unittest.skip(reason="MaskFormer is not a generative model"      )
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											pass






						@unittest.skip(reason="MaskFormer does not use token embeddings"      )
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											pass






						@require_torch_multi_gpu
						@unittest.skip(
						    reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`"      )
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											pass






						@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."      )
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											pass






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase       ,							__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__lowerCAmelCase           =	model_class(_A      )
																__lowerCAmelCase           =	inspect.signature(model.forward      )
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																__lowerCAmelCase           =	[*signature.parameters.keys()]

																__lowerCAmelCase           =	["pixel_values"]
																self.assertListEqual(arg_names[:1]		,      _A      )






						@slow
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											for model_name in ["facebook/maskformer-swin-small-coco"]:
																__lowerCAmelCase           =	MaskFormerModel.from_pretrained(_A      )
																self.assertIsNotNone(_A      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	(self.model_tester.min_size,) * 2
											__lowerCAmelCase           =	{
											    "pixel_values": torch.randn((2, 3, *size)		,      device=_A      ),
											    "mask_labels": torch.randn((2, 1_0, *size)		,      device=_A      ),
											    "class_labels": torch.zeros(2		,      1_0		,      device=_A      ).long(),
											}

											__lowerCAmelCase           =	MaskFormerForInstanceSegmentation(MaskFormerConfig()      ).to(_A      )
											__lowerCAmelCase           =	model(**_A      )
											self.assertTrue(outputs.loss is not None      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase       ,							__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.create_and_check_maskformer_model(_A		,      **_A		,      output_hidden_states=_A      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase       ,							__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__lowerCAmelCase           =	model_class(_A      ).to(_A      )
																__lowerCAmelCase           =	model(**_A		,      output_attentions=_A      )
																self.assertTrue(outputs.attentions is not None      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											if not self.model_tester.is_training:
																return
											# only MaskFormerForInstanceSegmentation has the loss
											__lowerCAmelCase           =	self.all_model_classes[1]
											__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs()

											__lowerCAmelCase           =	model_class(_A      )
											model.to(_A      )
											model.train()

											__lowerCAmelCase           =	model(_A		,      mask_labels=_A		,      class_labels=_A      ).loss
											loss.backward()






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	self.all_model_classes[1]
											__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase           =	self.model_tester.prepare_config_and_inputs()
											__lowerCAmelCase           =	True
											__lowerCAmelCase           =	True

											__lowerCAmelCase           =	model_class(_A      )
											model.to(_A      )
											model.train()

											__lowerCAmelCase           =	model(_A		,      mask_labels=_A		,      class_labels=_A      )

											__lowerCAmelCase           =	outputs.encoder_hidden_states[0]
											encoder_hidden_states.retain_grad()

											__lowerCAmelCase           =	outputs.pixel_decoder_hidden_states[0]
											pixel_decoder_hidden_states.retain_grad()
											# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
											__lowerCAmelCase           =	outputs.transformer_decoder_hidden_states[0]
											transformer_decoder_hidden_states.retain_grad()

											__lowerCAmelCase           =	outputs.attentions[0]
											attentions.retain_grad()

											outputs.loss.backward(retain_graph=_A      )

											self.assertIsNotNone(encoder_hidden_states.grad      )
											self.assertIsNotNone(pixel_decoder_hidden_states.grad      )
											self.assertIsNotNone(transformer_decoder_hidden_states.grad      )
											self.assertIsNotNone(attentions.grad      )






UpperCamelCase__         =      1E-4







def      _a				(						):
					__lowerCAmelCase           =	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
					return image


@require_vision
@slow
class       a__   ( unittest.TestCase				):






						@cached_property
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											return (
											    MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco"      )
											    if is_vision_available()
											    else None
											)






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco"      ).to(_A      )
											__lowerCAmelCase           =	self.default_image_processor
											__lowerCAmelCase           =	prepare_img()
											__lowerCAmelCase           =	image_processor(_A		,      return_tensors="pt"      ).to(_A      )
											__lowerCAmelCase           =	inputs["pixel_values"].shape
											# check size is divisible by 32
											self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0      )
											# check size
											self.assertEqual(_A		,      (1, 3, 8_0_0, 1_0_8_8)      )

											with torch.no_grad():
																__lowerCAmelCase           =	model(**_A      )

											__lowerCAmelCase           =	torch.tensor(
											    [[-0.04_82, 0.92_28, 0.49_51], [-0.25_47, 0.80_17, 0.85_27], [-0.00_69, 0.33_85, -0.00_89]]      ).to(_A      )
											self.assertTrue(
											    torch.allclose(
											        outputs.encoder_last_hidden_state[0, 0, :3, :3]		,      _A		,      atol=_A      )      )

											__lowerCAmelCase           =	torch.tensor(
											    [[-0.84_22, -0.84_34, -0.97_18], [-1.01_44, -0.55_65, -0.41_95], [-1.00_38, -0.44_84, -0.19_61]]      ).to(_A      )
											self.assertTrue(
											    torch.allclose(
											        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]		,      _A		,      atol=_A      )      )

											__lowerCAmelCase           =	torch.tensor(
											    [[0.28_52, -0.01_59, 0.97_35], [0.62_54, 0.18_58, 0.85_29], [-0.06_80, -0.41_16, 1.84_13]]      ).to(_A      )
											self.assertTrue(
											    torch.allclose(
											        outputs.transformer_decoder_last_hidden_state[0, :3, :3]		,      _A		,      atol=_A      )      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	(
											    MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco"      )
											    .to(_A      )
											    .eval()
											)
											__lowerCAmelCase           =	self.default_image_processor
											__lowerCAmelCase           =	prepare_img()
											__lowerCAmelCase           =	image_processor(_A		,      return_tensors="pt"      ).to(_A      )
											__lowerCAmelCase           =	inputs["pixel_values"].shape
											# check size is divisible by 32
											self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0      )
											# check size
											self.assertEqual(_A		,      (1, 3, 8_0_0, 1_0_8_8)      )

											with torch.no_grad():
																__lowerCAmelCase           =	model(**_A      )
											# masks_queries_logits
											__lowerCAmelCase           =	outputs.masks_queries_logits
											self.assertEqual(
											    masks_queries_logits.shape		,      (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)		,      )
											__lowerCAmelCase           =	[
											    [-1.3_73_71_24, -1.7_72_49_37, -1.9_36_42_33],
											    [-1.5_97_72_81, -1.9_86_79_39, -2.1_52_36_95],
											    [-1.5_79_53_98, -1.9_26_98_32, -2.09_39_42],
											]
											__lowerCAmelCase           =	torch.tensor(_A      ).to(_A      )
											self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]		,      _A		,      atol=_A      )      )
											# class_queries_logits
											__lowerCAmelCase           =	outputs.class_queries_logits
											self.assertEqual(
											    class_queries_logits.shape		,      (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)      )
											__lowerCAmelCase           =	torch.tensor(
											    [
											        [1.6_5_1_2E0_0, -5.2_5_7_2E0_0, -3.3_5_1_9E0_0],
											        [3.6_1_6_9E-0_2, -5.9_0_2_5E0_0, -2.9_3_1_3E0_0],
											        [1.0_7_6_6E-0_4, -7.7_6_3_0E0_0, -5.1_2_6_3E0_0],
											    ]      ).to(_A      )
											self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]		,      _A		,      atol=_A      )      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	(
											    MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff"      )
											    .to(_A      )
											    .eval()
											)
											__lowerCAmelCase           =	self.default_image_processor
											__lowerCAmelCase           =	prepare_img()
											__lowerCAmelCase           =	image_processor(_A		,      return_tensors="pt"      ).to(_A      )
											__lowerCAmelCase           =	inputs["pixel_values"].shape
											# check size is divisible by 32
											self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0      )
											# check size
											self.assertEqual(_A		,      (1, 3, 8_0_0, 1_0_8_8)      )

											with torch.no_grad():
																__lowerCAmelCase           =	model(**_A      )
											# masks_queries_logits
											__lowerCAmelCase           =	outputs.masks_queries_logits
											self.assertEqual(
											    masks_queries_logits.shape		,      (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)		,      )
											__lowerCAmelCase           =	[[-0.90_46, -2.63_66, -4.60_62], [-3.41_79, -5.78_90, -8.80_57], [-4.91_79, -7.65_60, -10.77_11]]
											__lowerCAmelCase           =	torch.tensor(_A      ).to(_A      )
											self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]		,      _A		,      atol=_A      )      )
											# class_queries_logits
											__lowerCAmelCase           =	outputs.class_queries_logits
											self.assertEqual(
											    class_queries_logits.shape		,      (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)      )
											__lowerCAmelCase           =	torch.tensor(
											    [[4.71_88, -3.25_85, -2.88_57], [6.68_71, -2.91_81, -1.24_87], [7.24_49, -2.27_64, -2.18_74]]      ).to(_A      )
											self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]		,      _A		,      atol=_A      )      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =	(
											    MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco"      )
											    .to(_A      )
											    .eval()
											)
											__lowerCAmelCase           =	self.default_image_processor

											__lowerCAmelCase           =	image_processor(
											    [np.zeros((3, 8_0_0, 1_3_3_3)      ), np.zeros((3, 8_0_0, 1_3_3_3)      )]		,      segmentation_maps=[np.zeros((3_8_4, 3_8_4)      ).astype(np.floataa      ), np.zeros((3_8_4, 3_8_4)      ).astype(np.floataa      )]		,      return_tensors="pt"		,      )

											__lowerCAmelCase           =	inputs["pixel_values"].to(_A      )
											__lowerCAmelCase           =	[el.to(_A      ) for el in inputs["mask_labels"]]
											__lowerCAmelCase           =	[el.to(_A      ) for el in inputs["class_labels"]]

											with torch.no_grad():
																__lowerCAmelCase           =	model(**_A      )

											self.assertTrue(outputs.loss is not None      )










import coval  # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401
from coval.conll import reader, util
from coval.eval import evaluator

import datasets


UpperCamelCase__         =      datasets.logging.get_logger(__name__)


UpperCamelCase__         =      """\
@InProceedings{moosavi2019minimum,
    author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},
    title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},
    year = {2019},
    booktitle = {Proceedings of the 57th Annual Meeting of
        the Association for Computational Linguistics (Volume 1: Long Papers)},
    publisher = {Association for Computational Linguistics},
    address = {Florence, Italy},
}

@inproceedings{10.3115/1072399.1072405,
author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},
title = {A Model-Theoretic Coreference Scoring Scheme},
year = {1995},
isbn = {1558604022},
publisher = {Association for Computational Linguistics},
address = {USA},
url = {https://doi.org/10.3115/1072399.1072405},
doi = {10.3115/1072399.1072405},
booktitle = {Proceedings of the 6th Conference on Message Understanding},
pages = {45–52},
numpages = {8},
location = {Columbia, Maryland},
series = {MUC6 ’95}
}

@INPROCEEDINGS{Bagga98algorithmsfor,
    author = {Amit Bagga and Breck Baldwin},
    title = {Algorithms for Scoring Coreference Chains},
    booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},
    year = {1998},
    pages = {563--566}
}

@INPROCEEDINGS{Luo05oncoreference,
    author = {Xiaoqiang Luo},
    title = {On coreference resolution performance metrics},
    booktitle = {In Proc. of HLT/EMNLP},
    year = {2005},
    pages = {25--32},
    publisher = {URL}
}

@inproceedings{moosavi-strube-2016-coreference,
    title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\",
    author = \"Moosavi, Nafise Sadat  and
      Strube, Michael\",
    booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\",
    month = aug,
    year = \"2016\",
    address = \"Berlin, Germany\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/P16-1060\",
    doi = \"10.18653/v1/P16-1060\",
    pages = \"632--642\",
}

"""

UpperCamelCase__         =      """\
CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which
implements of the common evaluation metrics including MUC [Vilain et al, 1995],
B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],
LEA [Moosavi and Strube, 2016] and the averaged CoNLL score
(the average of the F1 values of MUC, B-cubed and CEAFe)
[Denis and Baldridge, 2009a; Pradhan et al., 2011].

This wrapper of CoVal currently only work with CoNLL line format:
The CoNLL format has one word per line with all the annotation for this word in column separated by spaces:
Column	Type	Description
1	Document ID	This is a variation on the document filename
2	Part number	Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.
3	Word number
4	Word itself	This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.
5	Part-of-Speech
6	Parse bit	This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column.
7	Predicate lemma	The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\"
8	Predicate Frameset ID	This is the PropBank frameset ID of the predicate in Column 7.
9	Word sense	This is the word sense of the word in Column 3.
10	Speaker/Author	This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.
11	Named Entities	These columns identifies the spans representing various named entities.
12:N	Predicate Arguments	There is one column each of predicate argument structure information for the predicate mentioned in Column 7.
N	Coreference	Coreference chain information encoded in a parenthesis structure.
More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html

Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md

CoVal code was written by @ns-moosavi.
Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py
The test suite is taken from https://github.com/conll/reference-coreference-scorers/
Mention evaluation and the test suite are added by @andreasvc.
Parsing CoNLL files is developed by Leo Born.
"""

UpperCamelCase__         =      """
Calculates coreference evaluation metrics.
Args:
    predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.
        Each prediction is a word with its annotations as a string made of columns joined with spaces.
        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)
        See the details on the format in the description of the metric.
    references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.
        Each reference is a word with its annotations as a string made of columns joined with spaces.
        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)
        See the details on the format in the description of the metric.
    keep_singletons: After extracting all mentions of key or system files,
        mentions whose corresponding coreference chain is of size one,
        are considered as singletons. The default evaluation mode will include
        singletons in evaluations if they are included in the key or the system files.
        By setting 'keep_singletons=False', all singletons in the key and system files
        will be excluded from the evaluation.
    NP_only: Most of the recent coreference resolvers only resolve NP mentions and
        leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs.
    min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans.
        Minimum spans are determined using the MINA algorithm.

Returns:
    'mentions': mentions
    'muc': MUC metric [Vilain et al, 1995]
    'bcub': B-cubed [Bagga and Baldwin, 1998]
    'ceafe': CEAFe [Luo et al., 2005]
    'lea': LEA [Moosavi and Strube, 2016]
    'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)

Examples:

    >>> coval = datasets.load_metric('coval')
    >>> words = ['bc/cctv/00/cctv_0005   0   0       Thank   VBP  (TOP(S(VP*    thank  01   1    Xu_li  *           (V*)        *       -',
    ... 'bc/cctv/00/cctv_0005   0   1         you   PRP        (NP*)      -    -   -    Xu_li  *        (ARG1*)   (ARG0*)   (116)',
    ... 'bc/cctv/00/cctv_0005   0   2    everyone    NN        (NP*)      -    -   -    Xu_li  *    (ARGM-DIS*)        *    (116)',
    ... 'bc/cctv/00/cctv_0005   0   3         for    IN        (PP*       -    -   -    Xu_li  *        (ARG2*         *       -',
    ... 'bc/cctv/00/cctv_0005   0   4    watching   VBG   (S(VP*))))   watch  01   1    Xu_li  *             *)      (V*)      -',
    ... 'bc/cctv/00/cctv_0005   0   5           .     .          *))      -    -   -    Xu_li  *             *         *       -']
    >>> references = [words]
    >>> predictions = [words]
    >>> results = coval.compute(predictions=predictions, references=references)
    >>> print(results) # doctest:+ELLIPSIS
    {'mentions/recall': 1.0,[...] 'conll_score': 100.0}
"""







def      _a				(						SCREAMING_SNAKE_CASE_							:    Dict				,				SCREAMING_SNAKE_CASE_							:    Tuple				,				SCREAMING_SNAKE_CASE_							:    Dict=False				,				SCREAMING_SNAKE_CASE_							:    Any=False				,				SCREAMING_SNAKE_CASE_							:    str=True				,				SCREAMING_SNAKE_CASE_							:    int=False				,				SCREAMING_SNAKE_CASE_							:    Optional[int]="dummy_doc"					):
					__lowerCAmelCase           =	{doc: key_lines}
					__lowerCAmelCase           =	{doc: sys_lines}

					__lowerCAmelCase           =	{}

					__lowerCAmelCase           =	0
					__lowerCAmelCase           =	0
					__lowerCAmelCase           =	0
					__lowerCAmelCase           =	0
					__lowerCAmelCase           =	0
					__lowerCAmelCase           =	0

					__lowerCAmelCase       ,							__lowerCAmelCase           =	reader.get_doc_mentions(SCREAMING_SNAKE_CASE_				,				key_doc_lines[doc]				,				SCREAMING_SNAKE_CASE_					)
					key_singletons_num += singletons_num

					if NP_only or min_span:
										__lowerCAmelCase           =	reader.set_annotated_parse_trees(SCREAMING_SNAKE_CASE_				,				key_doc_lines[doc]				,				SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_					)

					__lowerCAmelCase       ,							__lowerCAmelCase           =	reader.get_doc_mentions(SCREAMING_SNAKE_CASE_				,				sys_doc_lines[doc]				,				SCREAMING_SNAKE_CASE_					)
					sys_singletons_num += singletons_num

					if NP_only or min_span:
										__lowerCAmelCase           =	reader.set_annotated_parse_trees(SCREAMING_SNAKE_CASE_				,				key_doc_lines[doc]				,				SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_					)

					if remove_nested:
										__lowerCAmelCase       ,							__lowerCAmelCase           =	reader.remove_nested_coref_mentions(SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_					)
										key_nested_coref_num += nested_mentions
										key_removed_nested_clusters += removed_clusters

										__lowerCAmelCase       ,							__lowerCAmelCase           =	reader.remove_nested_coref_mentions(SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_					)
										sys_nested_coref_num += nested_mentions
										sys_removed_nested_clusters += removed_clusters

					__lowerCAmelCase           =	reader.get_mention_assignments(SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_					)
					__lowerCAmelCase           =	reader.get_mention_assignments(SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_					)

					__lowerCAmelCase           =	(key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster)

					if remove_nested:
										logger.info(
										    "Number of removed nested coreferring mentions in the key "
										    F"""annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}"""					)
										logger.info(
										    "Number of resulting singleton clusters in the key "
										    F"""annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}"""					)

					if not keep_singletons:
										logger.info(
										    F"""{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system """
										    "files, respectively"					)

					return doc_coref_infos







def      _a				(						SCREAMING_SNAKE_CASE_							:    Tuple				,				SCREAMING_SNAKE_CASE_							:    Any				,				SCREAMING_SNAKE_CASE_							:    Any				,				SCREAMING_SNAKE_CASE_							:    str				,				SCREAMING_SNAKE_CASE_							:    List[Any]				,				SCREAMING_SNAKE_CASE_							:    Optional[int]				,				SCREAMING_SNAKE_CASE_							:    Optional[Any]					):
					__lowerCAmelCase           =	get_coref_infos(SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_					)

					__lowerCAmelCase           =	{}
					__lowerCAmelCase           =	0
					__lowerCAmelCase           =	0

					for name, metric in metrics:
										__lowerCAmelCase       ,							__lowerCAmelCase       ,							__lowerCAmelCase           =	evaluator.evaluate_documents(SCREAMING_SNAKE_CASE_				,				SCREAMING_SNAKE_CASE_				,				beta=1					)
										if name in ["muc", "bcub", "ceafe"]:
															conll += fa
															conll_subparts_num += 1
										output_scores.update({F"""{name}/recall""": recall, F"""{name}/precision""": precision, F"""{name}/f1""": fa}					)

										logger.info(
										    name.ljust(10					)				,				F"""Recall: {recall * 1_00:.2f}"""				,				F""" Precision: {precision * 1_00:.2f}"""				,				F""" F1: {fa * 1_00:.2f}"""				,				)

					if conll_subparts_num == 3:
										__lowerCAmelCase           =	(conll / 3) * 1_00
										logger.info(F"""CoNLL score: {conll:.2f}"""					)
										output_scores.update({"conll_score": conll}					)

					return output_scores







def      _a				(						SCREAMING_SNAKE_CASE_							:    List[str]					):
					__lowerCAmelCase           =	False
					for line in key_lines:
										if not line.startswith("#"					):
															if len(line.split()					) > 6:
																				__lowerCAmelCase           =	line.split()[5]
																				if not parse_col == "-":
																									__lowerCAmelCase           =	True
																									break
																				else:
																									break
					return has_gold_parse


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






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											return datasets.MetricInfo(
											    description=_DESCRIPTION		,      citation=_CITATION		,      inputs_description=_KWARGS_DESCRIPTION		,      features=datasets.Features(
											        {
											            "predictions": datasets.Sequence(datasets.Value("string"      )      ),
											            "references": datasets.Sequence(datasets.Value("string"      )      ),
											        }      )		,      codebase_urls=["https://github.com/ns-moosavi/coval"]		,      reference_urls=[
											        "https://github.com/ns-moosavi/coval",
											        "https://www.aclweb.org/anthology/P16-1060",
											        "http://www.conll.cemantix.org/2012/data.html",
											    ]		,      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A=True		,      _A=False		,      _A=False		,      _A=False      ):




											"""simple docstring"""



											__lowerCAmelCase           =	[
											    ("mentions", evaluator.mentions),
											    ("muc", evaluator.muc),
											    ("bcub", evaluator.b_cubed),
											    ("ceafe", evaluator.ceafe),
											    ("lea", evaluator.lea),
											]

											if min_span:
																__lowerCAmelCase           =	util.check_gold_parse_annotation(_A      )
																if not has_gold_parse:
																					raise NotImplementedError("References should have gold parse annotation to use 'min_span'."      )
																					# util.parse_key_file(key_file)
																					# key_file = key_file + ".parsed"

											__lowerCAmelCase           =	evaluate(
											    key_lines=_A		,      sys_lines=_A		,      metrics=_A		,      NP_only=_A		,      remove_nested=_A		,      keep_singletons=_A		,      min_span=_A		,      )

											return score




