

import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VideoMAEConfig
from transformers.models.auto import get_values
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_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch
     from torch import nn

     from transformers import (
         MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
         VideoMAEForPreTraining,
         VideoMAEForVideoClassification,
         VideoMAEModel,
     )
     from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from transformers import VideoMAEImageProcessor





class  __UpperCAmelCase					:



   def __init__(							self							:					Union[str, Any],		__A							:					int,		__A							:					Union[str, Any]=1_3,		__A							:					Optional[int]=1_0,		__A							:					str=3,		__A							:					int=2,		__A							:					List[str]=2,		__A							:					Tuple=2,		__A							:					Dict=True,		__A							:					Tuple=True,		__A							:					List[Any]=3_2,		__A							:					List[Any]=5,		__A							:					str=4,		__A							:					Dict=3_7,		__A							:					int="gelu",		__A							:					List[str]=0.1,		__A							:					Any=0.1,		__A							:					Any=1_0,		__A							:					int=0.0_2,		__A							:					Union[str, Any]=0.9,		__A							:					Union[str, Any]=None,		):
     UpperCAmelCase	:							Tuple						=			parent
     UpperCAmelCase	:							str						=			batch_size
     UpperCAmelCase	:							str						=			image_size
     UpperCAmelCase	:							List[Any]						=			num_channels
     UpperCAmelCase	:							Optional[Any]						=			patch_size
     UpperCAmelCase	:							Tuple						=			tubelet_size
     UpperCAmelCase	:							int						=			num_frames
     UpperCAmelCase	:							str						=			is_training
     UpperCAmelCase	:							int						=			use_labels
     UpperCAmelCase	:							Any						=			hidden_size
     UpperCAmelCase	:							Any						=			num_hidden_layers
     UpperCAmelCase	:							Optional[int]						=			num_attention_heads
     UpperCAmelCase	:							Dict						=			intermediate_size
     UpperCAmelCase	:							Tuple						=			hidden_act
     UpperCAmelCase	:							Dict						=			hidden_dropout_prob
     UpperCAmelCase	:							Any						=			attention_probs_dropout_prob
     UpperCAmelCase	:							int						=			type_sequence_label_size
     UpperCAmelCase	:							Dict						=			initializer_range
     UpperCAmelCase	:							Union[str, Any]						=			mask_ratio
     UpperCAmelCase	:							List[Any]						=			scope

     # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
     UpperCAmelCase	:							str						=			(image_size // patch_size) ** 2
     UpperCAmelCase	:							int						=			(num_frames // tubelet_size) * self.num_patches_per_frame

     # use this variable to define bool_masked_pos
     UpperCAmelCase	:							List[str]						=			int(mask_ratio * self.seq_length						)



   def 	__magic_name__   (							self							:					str						):
     UpperCAmelCase	:							Optional[int]						=			floats_tensor(
         [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]						)

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

     UpperCAmelCase	:							Any						=			self.get_config()

     return config, pixel_values, labels



   def 	__magic_name__   (							self							:					Any						):
     return VideoMAEConfig(
         image_size=self.image_size,		patch_size=self.patch_size,		num_channels=self.num_channels,		num_frames=self.num_frames,		tubelet_size=self.tubelet_size,		hidden_size=self.hidden_size,		num_hidden_layers=self.num_hidden_layers,		num_attention_heads=self.num_attention_heads,		intermediate_size=self.intermediate_size,		hidden_act=self.hidden_act,		hidden_dropout_prob=self.hidden_dropout_prob,		attention_probs_dropout_prob=self.attention_probs_dropout_prob,		is_decoder=__A,		initializer_range=self.initializer_range,		)



   def 	__magic_name__   (							self							:					str,		__A							:					Optional[int],		__A							:					int,		__A							:					List[Any]						):
     UpperCAmelCase	:							List[str]						=			VideoMAEModel(config=__A						)
     model.to(__A						)
     model.eval()
     UpperCAmelCase	:							List[Any]						=			model(__A						)
     self.parent.assertEqual(result.last_hidden_state.shape,		(self.batch_size, self.seq_length, self.hidden_size)						)



   def 	__magic_name__   (							self							:					Optional[int],		__A							:					int,		__A							:					Dict,		__A							:					str						):
     UpperCAmelCase	:							List[str]						=			VideoMAEForPreTraining(__A						)
     model.to(__A						)
     model.eval()
     # important: each video needs to have the same number of masked patches
     # hence we define a single mask, which we then repeat for each example in the batch
     UpperCAmelCase	:							str						=			torch.ones((self.num_masks,)						)
     UpperCAmelCase	:							Optional[Any]						=			torch.cat([mask, torch.zeros(self.seq_length - mask.size(0						)						)]						)
     UpperCAmelCase	:							Optional[int]						=			mask.expand(self.batch_size,		-1						).bool()

     UpperCAmelCase	:							str						=			model(__A,		__A						)
     # model only returns predictions for masked patches
     UpperCAmelCase	:							Dict						=			mask.sum().item()
     UpperCAmelCase	:							Dict						=			3 * self.tubelet_size * self.patch_size**2
     self.parent.assertEqual(result.logits.shape,		(self.batch_size, num_masked_patches, decoder_num_labels)						)





   def 	__magic_name__   (							self							:					List[str]						):
     UpperCAmelCase	:							Optional[int]						=			self.prepare_config_and_inputs()
     UpperCAmelCase			,						UpperCAmelCase			,						UpperCAmelCase	:							Optional[Any]						=			config_and_inputs
     UpperCAmelCase	:							int						=			{'''pixel_values''': pixel_values}
     return config, inputs_dict






@require_torch
class  __UpperCAmelCase					(	lowerCamelCase__      ,  lowerCamelCase__      ,  unittest.TestCase						):
   UpperCamelCase       					=					(
       (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
   )
   UpperCamelCase       					=					(
       {"""feature-extraction""": VideoMAEModel, """video-classification""": VideoMAEForVideoClassification}
       if is_torch_available()
       else {}
   )

   UpperCamelCase       					=					False
   UpperCamelCase       					=					False
   UpperCamelCase       					=					False
   UpperCamelCase       					=					False



   def 	__magic_name__   (							self							:					Any						):
     UpperCAmelCase	:							str						=			VideoMAEModelTester(self						)
     UpperCAmelCase	:							Any						=			ConfigTester(self,		config_class=__A,		has_text_modality=__A,		hidden_size=3_7						)



   def 	__magic_name__   (							self							:					Tuple,		__A							:					Tuple,		__A							:					str,		__A							:					Tuple=False						):
     UpperCAmelCase	:							Tuple						=			copy.deepcopy(__A						)

     if model_class == VideoMAEForPreTraining:
       # important: each video needs to have the same number of masked patches
       # hence we define a single mask, which we then repeat for each example in the batch
       UpperCAmelCase	:							Dict						=			torch.ones((self.model_tester.num_masks,)						)
       UpperCAmelCase	:							int						=			torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0						)						)]						)
       UpperCAmelCase	:							Union[str, Any]						=			mask.expand(self.model_tester.batch_size,		-1						).bool()
       UpperCAmelCase	:							Dict						=			bool_masked_pos.to(__A						)

     if return_labels:
       if model_class in [
           *get_values(__A						),
       ]:
         UpperCAmelCase	:							Union[str, Any]						=			torch.zeros(
             self.model_tester.batch_size,		dtype=torch.long,		device=__A						)

     return inputs_dict



   def 	__magic_name__   (							self							:					Any						):
     self.config_tester.run_common_tests()



   @unittest.skip(reason='''VideoMAE does not use inputs_embeds'''						)
   def 	__magic_name__   (							self							:					List[str]						):
     pass



   def 	__magic_name__   (							self							:					List[Any]						):
     UpperCAmelCase			,						UpperCAmelCase	:							int						=			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       UpperCAmelCase	:							List[Any]						=			model_class(__A						)
       self.assertIsInstance(model.get_input_embeddings(),		(nn.Module)						)
       UpperCAmelCase	:							Tuple						=			model.get_output_embeddings()
       self.assertTrue(x is None or isinstance(__A,		nn.Linear						)						)



   def 	__magic_name__   (							self							:					List[Any]						):
     UpperCAmelCase			,						UpperCAmelCase	:							Tuple						=			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       UpperCAmelCase	:							Optional[Any]						=			model_class(__A						)
       UpperCAmelCase	:							Tuple						=			inspect.signature(model.forward						)
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       UpperCAmelCase	:							List[str]						=			[*signature.parameters.keys()]

       UpperCAmelCase	:							Tuple						=			['''pixel_values''']
       self.assertListEqual(arg_names[:1],		__A						)



   def 	__magic_name__   (							self							:					Any						):
     UpperCAmelCase	:							Any						=			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__A						)



   def 	__magic_name__   (							self							:					Optional[int]						):
     UpperCAmelCase	:							Union[str, Any]						=			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_pretraining(*__A						)



   @slow
   def 	__magic_name__   (							self							:					str						):
     for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase	:							Tuple						=			VideoMAEModel.from_pretrained(__A						)
       self.assertIsNotNone(__A						)



   def 	__magic_name__   (							self							:					Optional[Any]						):
     if not self.has_attentions:
       pass

     else:
       UpperCAmelCase			,						UpperCAmelCase	:							int						=			self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase	:							Optional[Any]						=			True

       for model_class in self.all_model_classes:
         UpperCAmelCase	:							Union[str, Any]						=			self.model_tester.seq_length - self.model_tester.num_masks
         UpperCAmelCase	:							str						=			(
             num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
         )

         UpperCAmelCase	:							Any						=			True
         UpperCAmelCase	:							Tuple						=			False
         UpperCAmelCase	:							Union[str, Any]						=			True
         UpperCAmelCase	:							Optional[Any]						=			model_class(__A						)
         model.to(__A						)
         model.eval()
         with torch.no_grad():
           UpperCAmelCase	:							Tuple						=			model(**self._prepare_for_class(__A,		__A						)						)
         UpperCAmelCase	:							int						=			outputs.attentions
         self.assertEqual(len(__A						),		self.model_tester.num_hidden_layers						)

         # check that output_attentions also work using config
         del inputs_dict["output_attentions"]
         UpperCAmelCase	:							int						=			True
         UpperCAmelCase	:							str						=			model_class(__A						)
         model.to(__A						)
         model.eval()
         with torch.no_grad():
           UpperCAmelCase	:							Optional[Any]						=			model(**self._prepare_for_class(__A,		__A						)						)
         UpperCAmelCase	:							Any						=			outputs.attentions
         self.assertEqual(len(__A						),		self.model_tester.num_hidden_layers						)

         self.assertListEqual(
             list(attentions[0].shape[-3:]						),		[self.model_tester.num_attention_heads, seq_len, seq_len],		)
         UpperCAmelCase	:							Any						=			len(__A						)

         # Check attention is always last and order is fine
         UpperCAmelCase	:							int						=			True
         UpperCAmelCase	:							Union[str, Any]						=			True
         UpperCAmelCase	:							List[Any]						=			model_class(__A						)
         model.to(__A						)
         model.eval()
         with torch.no_grad():
           UpperCAmelCase	:							str						=			model(**self._prepare_for_class(__A,		__A						)						)

         self.assertEqual(out_len + 1,		len(__A						)						)

         UpperCAmelCase	:							Dict						=			outputs.attentions

         self.assertEqual(len(__A						),		self.model_tester.num_hidden_layers						)
         self.assertListEqual(
             list(self_attentions[0].shape[-3:]						),		[self.model_tester.num_attention_heads, seq_len, seq_len],		)



   def 	__magic_name__   (							self							:					Dict						):
     def check_hidden_states_output(__A							:					Any,		__A							:					Optional[int],		__A							:					List[str]						):
       UpperCAmelCase	:							List[Any]						=			model_class(__A						)
       model.to(__A						)
       model.eval()

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

       UpperCAmelCase	:							List[Any]						=			outputs.hidden_states
       UpperCAmelCase	:							Dict						=			self.model_tester.num_hidden_layers + 1
       self.assertEqual(len(__A						),		__A						)

       UpperCAmelCase	:							Optional[int]						=			self.model_tester.seq_length - self.model_tester.num_masks
       UpperCAmelCase	:							Optional[Any]						=			num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

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

     UpperCAmelCase			,						UpperCAmelCase	:							Union[str, Any]						=			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       UpperCAmelCase	:							Any						=			True
       check_hidden_states_output(__A,		__A,		__A						)

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

       check_hidden_states_output(__A,		__A,		__A						)





   @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''						)
   def 	__magic_name__   (							self							:					str						):
     pass






def       a__					(		)  ->						Dict:
  UpperCAmelCase	:							Any						=			hf_hub_download(
      repo_id='''hf-internal-testing/spaghetti-video'''    ,			filename='''eating_spaghetti.npy'''    ,			repo_type='''dataset'''      )
  UpperCAmelCase	:							int						=			np.load(UpperCAmelCase      )
  return list(UpperCAmelCase      )






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



   @cached_property
   def 	__magic_name__   (							self							:					List[Any]						):
     # logits were tested with a different mean and std, so we use the same here
     return (
         VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5],		image_std=[0.5, 0.5, 0.5]						)
         if is_vision_available()
         else None
     )



   @slow
   def 	__magic_name__   (							self							:					str						):
     UpperCAmelCase	:							Dict						=			VideoMAEForVideoClassification.from_pretrained('''MCG-NJU/videomae-base-finetuned-kinetics'''						).to(
         __A						)

     UpperCAmelCase	:							Any						=			self.default_image_processor
     UpperCAmelCase	:							int						=			prepare_video()
     UpperCAmelCase	:							str						=			image_processor(__A,		return_tensors='''pt'''						).to(__A						)

     # forward pass
     with torch.no_grad():
       UpperCAmelCase	:							Dict						=			model(**__A						)

     # verify the logits
     UpperCAmelCase	:							Optional[Any]						=			torch.Size((1, 4_0_0)						)
     self.assertEqual(outputs.logits.shape,		__A						)

     UpperCAmelCase	:							Dict						=			torch.tensor([0.3_6_6_9, -0.0_6_8_8, -0.2_4_2_1]						).to(__A						)

     self.assertTrue(torch.allclose(outputs.logits[0, :3],		__A,		atol=1E-4						)						)





   @slow
   def 	__magic_name__   (							self							:					str						):
     UpperCAmelCase	:							Dict						=			VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short'''						).to(__A						)

     UpperCAmelCase	:							Optional[Any]						=			self.default_image_processor
     UpperCAmelCase	:							List[Any]						=			prepare_video()
     UpperCAmelCase	:							List[str]						=			image_processor(__A,		return_tensors='''pt'''						).to(__A						)

     # add boolean mask, indicating which patches to mask
     UpperCAmelCase	:							str						=			hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos''',		filename='''bool_masked_pos.pt'''						)
     UpperCAmelCase	:							List[Any]						=			torch.load(__A						)

     # forward pass
     with torch.no_grad():
       UpperCAmelCase	:							Dict						=			model(**__A						)

     # verify the logits
     UpperCAmelCase	:							List[str]						=			torch.Size([1, 1_4_0_8, 1_5_3_6]						)
     UpperCAmelCase	:							Tuple						=			torch.tensor(
         [[0.7_9_9_4, 0.9_6_1_2, 0.8_5_0_8], [0.7_4_0_1, 0.8_9_5_8, 0.8_3_0_2], [0.5_8_6_2, 0.7_4_6_8, 0.7_3_2_5]],		device=__A						)
     self.assertEqual(outputs.logits.shape,		__A						)
     self.assertTrue(torch.allclose(outputs.logits[0, :3, :3],		__A,		atol=1E-4						)						)

     # verify the loss (`config.norm_pix_loss` = `True`)
     UpperCAmelCase	:							Union[str, Any]						=			torch.tensor([0.5_1_4_2],		device=__A						)
     self.assertTrue(torch.allclose(outputs.loss,		__A,		atol=1E-4						)						)

     # verify the loss (`config.norm_pix_loss` = `False`)
     UpperCAmelCase	:							Union[str, Any]						=			VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''',		norm_pix_loss=__A						).to(
         __A						)

     with torch.no_grad():
       UpperCAmelCase	:							str						=			model(**__A						)

     UpperCAmelCase	:							List[Any]						=			torch.tensor(torch.tensor([0.6_4_6_9]						),		device=__A						)
     self.assertTrue(torch.allclose(outputs.loss,		__A,		atol=1E-4						)						)








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


_lowerCamelCase    :       int        =							datasets.logging.get_logger(__name__)


_lowerCamelCase    :       Any        =							"\\n@InProceedings{moosavi2019minimum,\n    author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n    title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n    year = {2019},\n    booktitle = {Proceedings of the 57th Annual Meeting of\n        the Association for Computational Linguistics (Volume 1: Long Papers)},\n    publisher = {Association for Computational Linguistics},\n    address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n    author = {Amit Bagga and Breck Baldwin},\n    title = {Algorithms for Scoring Coreference Chains},\n    booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n    year = {1998},\n    pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n    author = {Xiaoqiang Luo},\n    title = {On coreference resolution performance metrics},\n    booktitle = {In Proc. of HLT/EMNLP},\n    year = {2005},\n    pages = {25--32},\n    publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n    title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\",\n    author = \"Moosavi, Nafise Sadat  and\n      Strube, Michael\",\n    booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\",\n    month = aug,\n    year = \"2016\",\n    address = \"Berlin, Germany\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/P16-1060\",\n    doi = \"10.18653/v1/P16-1060\",\n    pages = \"632--642\",\n}\n\n"

_lowerCamelCase    :       Tuple        =							"\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn	Type	Description\n1	Document ID	This is a variation on the document filename\n2	Part number	Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3	Word number\n4	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.\n5	Part-of-Speech\n6	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.\n7	Predicate lemma	The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\"\n8	Predicate Frameset ID	This is the PropBank frameset ID of the predicate in Column 7.\n9	Word sense	This is the word sense of the word in Column 3.\n10	Speaker/Author	This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11	Named Entities	These columns identifies the spans representing various named entities.\n12:N	Predicate Arguments	There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN	Coreference	Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n"

_lowerCamelCase    :       List[str]        =							"\nCalculates coreference evaluation metrics.\nArgs:\n    predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n        Each prediction is a word with its annotations as a string made of columns joined with spaces.\n        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n        See the details on the format in the description of the metric.\n    references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n        Each reference is a word with its annotations as a string made of columns joined with spaces.\n        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n        See the details on the format in the description of the metric.\n    keep_singletons: After extracting all mentions of key or system files,\n        mentions whose corresponding coreference chain is of size one,\n        are considered as singletons. The default evaluation mode will include\n        singletons in evaluations if they are included in the key or the system files.\n        By setting 'keep_singletons=False', all singletons in the key and system files\n        will be excluded from the evaluation.\n    NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n        leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs.\n    min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans.\n        Minimum spans are determined using the MINA algorithm.\n\nReturns:\n    'mentions': mentions\n    'muc': MUC metric [Vilain et al, 1995]\n    'bcub': B-cubed [Bagga and Baldwin, 1998]\n    'ceafe': CEAFe [Luo et al., 2005]\n    'lea': LEA [Moosavi and Strube, 2016]\n    'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n    >>> coval = datasets.load_metric('coval')\n    >>> words = ['bc/cctv/00/cctv_0005   0   0       Thank   VBP  (TOP(S(VP*    thank  01   1    Xu_li  *           (V*)        *       -',\n    ... 'bc/cctv/00/cctv_0005   0   1         you   PRP        (NP*)      -    -   -    Xu_li  *        (ARG1*)   (ARG0*)   (116)',\n    ... 'bc/cctv/00/cctv_0005   0   2    everyone    NN        (NP*)      -    -   -    Xu_li  *    (ARGM-DIS*)        *    (116)',\n    ... 'bc/cctv/00/cctv_0005   0   3         for    IN        (PP*       -    -   -    Xu_li  *        (ARG2*         *       -',\n    ... 'bc/cctv/00/cctv_0005   0   4    watching   VBG   (S(VP*))))   watch  01   1    Xu_li  *             *)      (V*)      -',\n    ... 'bc/cctv/00/cctv_0005   0   5           .     .          *))      -    -   -    Xu_li  *             *         *       -']\n    >>> references = [words]\n    >>> predictions = [words]\n    >>> results = coval.compute(predictions=predictions, references=references)\n    >>> print(results) # doctest:+ELLIPSIS\n    {'mentions/recall': 1.0,[...] 'conll_score': 100.0}\n"

def       a__					(		UpperCAmelCase							:      int    ,			UpperCAmelCase							:      str    ,			UpperCAmelCase							:      Union[str, Any]=False    ,			UpperCAmelCase							:      Optional[Any]=False    ,			UpperCAmelCase							:      Optional[Any]=True    ,			UpperCAmelCase							:      List[str]=False    ,			UpperCAmelCase							:      List[str]="dummy_doc"      )  ->						Any:
  UpperCAmelCase	:							Dict						=			{doc: key_lines}
  UpperCAmelCase	:							Any						=			{doc: sys_lines}

  UpperCAmelCase	:							int						=			{}

  UpperCAmelCase	:							List[Any]						=			0
  UpperCAmelCase	:							Any						=			0
  UpperCAmelCase	:							Optional[int]						=			0
  UpperCAmelCase	:							Optional[Any]						=			0
  UpperCAmelCase	:							int						=			0
  UpperCAmelCase	:							List[str]						=			0

  UpperCAmelCase			,						UpperCAmelCase	:							Tuple						=			reader.get_doc_mentions(UpperCAmelCase    ,			key_doc_lines[doc]    ,			UpperCAmelCase      )
  key_singletons_num += singletons_num

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

  UpperCAmelCase			,						UpperCAmelCase	:							str						=			reader.get_doc_mentions(UpperCAmelCase    ,			sys_doc_lines[doc]    ,			UpperCAmelCase      )
  sys_singletons_num += singletons_num

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

  if remove_nested:
    UpperCAmelCase			,						UpperCAmelCase	:							Tuple						=			reader.remove_nested_coref_mentions(UpperCAmelCase    ,			UpperCAmelCase      )
    key_nested_coref_num += nested_mentions
    key_removed_nested_clusters += removed_clusters

    UpperCAmelCase			,						UpperCAmelCase	:							List[str]						=			reader.remove_nested_coref_mentions(UpperCAmelCase    ,			UpperCAmelCase      )
    sys_nested_coref_num += nested_mentions
    sys_removed_nested_clusters += removed_clusters

  UpperCAmelCase	:							Union[str, Any]						=			reader.get_mention_assignments(UpperCAmelCase    ,			UpperCAmelCase      )
  UpperCAmelCase	:							Optional[int]						=			reader.get_mention_assignments(UpperCAmelCase    ,			UpperCAmelCase      )

  UpperCAmelCase	:							str						=			(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__					(		UpperCAmelCase							:      Tuple    ,			UpperCAmelCase							:      Optional[Any]    ,			UpperCAmelCase							:      Dict    ,			UpperCAmelCase							:      List[str]    ,			UpperCAmelCase							:      Tuple    ,			UpperCAmelCase							:      int    ,			UpperCAmelCase							:      Optional[Any]      )  ->						Union[str, Any]:
  UpperCAmelCase	:							Optional[int]						=			get_coref_infos(UpperCAmelCase    ,			UpperCAmelCase    ,			UpperCAmelCase    ,			UpperCAmelCase    ,			UpperCAmelCase    ,			UpperCAmelCase      )

  UpperCAmelCase	:							Dict						=			{}
  UpperCAmelCase	:							Dict						=			0
  UpperCAmelCase	:							Tuple						=			0

  for name, metric in metrics:
    UpperCAmelCase			,						UpperCAmelCase			,						UpperCAmelCase	:							List[str]						=			evaluator.evaluate_documents(UpperCAmelCase    ,			UpperCAmelCase    ,			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 * 100:.2f}'''    ,			f''' Precision: {precision * 100:.2f}'''    ,			f''' F1: {fa * 100:.2f}'''    ,			)

  if conll_subparts_num == 3:
    UpperCAmelCase	:							Optional[int]						=			(conll / 3) * 100
    logger.info(f'''CoNLL score: {conll:.2f}'''      )
    output_scores.update({'''conll_score''': conll}      )

  return output_scores

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






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



   def 	__magic_name__   (							self							:					Union[str, Any]						):
     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 	__magic_name__   (							self							:					str,		__A							:					Any,		__A							:					Dict,		__A							:					List[str]=True,		__A							:					Optional[Any]=False,		__A							:					List[Any]=False,		__A							:					Tuple=False						):
     UpperCAmelCase	:							Optional[Any]						=			[
         ('''mentions''', evaluator.mentions),
         ('''muc''', evaluator.muc),
         ('''bcub''', evaluator.b_cubed),
         ('''ceafe''', evaluator.ceafe),
         ('''lea''', evaluator.lea),
     ]

     if min_span:
       UpperCAmelCase	:							List[Any]						=			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"

     UpperCAmelCase	:							Union[str, Any]						=			evaluate(
         key_lines=__A,		sys_lines=__A,		metrics=__A,		NP_only=__A,		remove_nested=__A,		keep_singletons=__A,		min_span=__A,		)

     return score





