



import importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


A__								=						(
    '''https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'''
)


A__								=						logging.get_logger(__name__)  # pylint: disable=invalid-name



def 			_lowerCAmelCase       (					)   ->					Union[str, Any]:


				"""simple docstring"""

				snake_case__	:      List[str]     		=	'''https://pypi.org/pypi/diffusers/json'''
				snake_case__	:      str     		=	json.loads(request.urlopen(__lowerCAmelCase      ).read()      )['''releases'''].keys()
				return sorted(__lowerCAmelCase  ,  key=lambda __lowerCAmelCase      : version.Version(__lowerCAmelCase      )      )



def 			_lowerCAmelCase       (					)   ->					Optional[int]:


				"""simple docstring"""

				if HF_MODULES_CACHE in sys.path:
								return

				sys.path.append(__lowerCAmelCase      )
				os.makedirs(__lowerCAmelCase  ,  exist_ok=__lowerCAmelCase      )
				snake_case__	:      int     		=	Path(__lowerCAmelCase      ) / '''__init__.py'''
				if not init_path.exists():
								init_path.touch()



def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					str:


				"""simple docstring"""

				init_hf_modules()
				snake_case__	:      Dict     		=	Path(__lowerCAmelCase      ) / name
				# If the parent module does not exist yet, recursively create it.
				if not dynamic_module_path.parent.exists():
								create_dynamic_module(dynamic_module_path.parent      )
				os.makedirs(__lowerCAmelCase  ,  exist_ok=__lowerCAmelCase      )
				snake_case__	:      List[str]     		=	dynamic_module_path / '''__init__.py'''
				if not init_path.exists():
								init_path.touch()



def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					List[str]:


				"""simple docstring"""

				with open(__lowerCAmelCase  ,  '''r'''  ,  encoding='''utf-8'''      ) as f:
								snake_case__	:      int     		=	f.read()

				# Imports of the form `import .xxx`
				snake_case__	:      List[str]     		=	re.findall('''^\s*import\s+\.(\S+)\s*$'''  ,  __lowerCAmelCase  ,  flags=re.MULTILINE      )
				# Imports of the form `from .xxx import yyy`
				relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import'''  ,  __lowerCAmelCase  ,  flags=re.MULTILINE      )
				# Unique-ify
				return list(set(__lowerCAmelCase      )      )



def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					str:


				"""simple docstring"""

				snake_case__	:      Optional[Any]     		=	False
				snake_case__	:      Dict     		=	[module_file]
				snake_case__	:      Optional[Any]     		=	[]

				# Let's recurse through all relative imports
				while not no_change:
								snake_case__	:      int     		=	[]
								for f in files_to_check:
												new_imports.extend(get_relative_imports(__lowerCAmelCase      )      )

								snake_case__	:      Union[str, Any]     		=	Path(__lowerCAmelCase      ).parent
								snake_case__	:      List[Any]     		=	[str(module_path / m      ) for m in new_imports]
								snake_case__	:      Optional[int]     		=	[f for f in new_import_files if f not in all_relative_imports]
								snake_case__	:      int     		=	[f"""{f}.py""" for f in new_import_files]

								snake_case__	:      Dict     		=	len(__lowerCAmelCase      ) == 0
								all_relative_imports.extend(__lowerCAmelCase      )

				return all_relative_imports



def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					Dict:


				"""simple docstring"""

				with open(__lowerCAmelCase  ,  '''r'''  ,  encoding='''utf-8'''      ) as f:
								snake_case__	:      Optional[int]     		=	f.read()

				# Imports of the form `import xxx`
				snake_case__	:      str     		=	re.findall('''^\s*import\s+(\S+)\s*$'''  ,  __lowerCAmelCase  ,  flags=re.MULTILINE      )
				# Imports of the form `from xxx import yyy`
				imports += re.findall('''^\s*from\s+(\S+)\s+import'''  ,  __lowerCAmelCase  ,  flags=re.MULTILINE      )
				# Only keep the top-level module
				snake_case__	:      str     		=	[imp.split('''.'''      )[0] for imp in imports if not imp.startswith('''.'''      )]

				# Unique-ify and test we got them all
				snake_case__	:      Optional[Any]     		=	list(set(__lowerCAmelCase      )      )
				snake_case__	:      int     		=	[]
				for imp in imports:
								try:
												importlib.import_module(__lowerCAmelCase      )
								except ImportError:
												missing_packages.append(__lowerCAmelCase      )

				if len(__lowerCAmelCase      ) > 0:
								raise ImportError(
								    '''This modeling file requires the following packages that were not found in your environment: '''
								    f"""{', '.join(__lowerCAmelCase      )}. Run `pip install {' '.join(__lowerCAmelCase      )}`"""      )

				return get_relative_imports(__lowerCAmelCase      )



def 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase      )   ->					Any:


				"""simple docstring"""

				snake_case__	:      Optional[int]     		=	module_path.replace(os.path.sep  ,  '''.'''      )
				snake_case__	:      Dict     		=	importlib.import_module(__lowerCAmelCase      )

				if class_name is None:
								return find_pipeline_class(__lowerCAmelCase      )
				return getattr(__lowerCAmelCase  ,  __lowerCAmelCase      )



def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					Any:


				"""simple docstring"""

				from ..pipelines import DiffusionPipeline

				snake_case__	:      List[Any]     		=	dict(inspect.getmembers(__lowerCAmelCase  ,  inspect.isclass      )      )

				snake_case__	:      Optional[int]     		=	None
				for cls_name, cls in cls_members.items():
								if (
								    cls_name != DiffusionPipeline.__name__
								    and issubclass(cls  ,  __lowerCAmelCase      )
								    and cls.__module__.split('''.'''      )[0] != "diffusers"
								):
												if pipeline_class is not None:
																raise ValueError(
																    f"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:"""
																    f""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in"""
																    f""" {loaded_module}."""      )
												snake_case__	:      List[Any]     		=	cls

				return pipeline_class



def 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = False  ,  __lowerCAmelCase = False  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = False  ,  )   ->					int:


				"""simple docstring"""

				snake_case__	:      List[str]     		=	str(__lowerCAmelCase      )

				snake_case__	:      List[Any]     		=	os.path.join(__lowerCAmelCase  ,  __lowerCAmelCase      )

				if os.path.isfile(__lowerCAmelCase      ):
								snake_case__	:      List[str]     		=	module_file_or_url
								snake_case__	:      Union[str, Any]     		=	'''local'''
				elif pretrained_model_name_or_path.count('''/'''      ) == 0:
								snake_case__	:      Any     		=	get_diffusers_versions()
								# cut ".dev0"
								snake_case__	:      int     		=	'''v''' + '''.'''.join(__version__.split('''.'''      )[:3]      )

								# retrieve github version that matches
								if revision is None:
												snake_case__	:      List[str]     		=	latest_version if latest_version[1:] in available_versions else '''main'''
												logger.info(f"""Defaulting to latest_version: {revision}."""      )
								elif revision in available_versions:
												snake_case__	:      str     		=	f"""v{revision}"""
								elif revision == "main":
												snake_case__	:      List[Any]     		=	revision
								else:
												raise ValueError(
												    f"""`custom_revision`: {revision} does not exist. Please make sure to choose one of"""
												    f""" {', '.join(available_versions + ['main']      )}."""      )

								# community pipeline on GitHub
								snake_case__	:      List[str]     		=	COMMUNITY_PIPELINES_URL.format(revision=__lowerCAmelCase  ,  pipeline=__lowerCAmelCase      )
								try:
												snake_case__	:      List[str]     		=	cached_download(
												    __lowerCAmelCase  ,  cache_dir=__lowerCAmelCase  ,  force_download=__lowerCAmelCase  ,  proxies=__lowerCAmelCase  ,  resume_download=__lowerCAmelCase  ,  local_files_only=__lowerCAmelCase  ,  use_auth_token=__lowerCAmelCase  ,  )
												snake_case__	:      int     		=	'''git'''
												snake_case__	:      Union[str, Any]     		=	pretrained_model_name_or_path + '''.py'''
								except EnvironmentError:
												logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}."""      )
												raise
				else:
								try:
												# Load from URL or cache if already cached
												snake_case__	:      Any     		=	hf_hub_download(
												    __lowerCAmelCase  ,  __lowerCAmelCase  ,  cache_dir=__lowerCAmelCase  ,  force_download=__lowerCAmelCase  ,  proxies=__lowerCAmelCase  ,  resume_download=__lowerCAmelCase  ,  local_files_only=__lowerCAmelCase  ,  use_auth_token=__lowerCAmelCase  ,  )
												snake_case__	:      List[Any]     		=	os.path.join('''local'''  ,  '''--'''.join(pretrained_model_name_or_path.split('''/'''      )      )      )
								except EnvironmentError:
												logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}."""      )
												raise

    # Check we have all the requirements in our environment
				snake_case__	:      Optional[int]     		=	check_imports(__lowerCAmelCase      )

				# Now we move the module inside our cached dynamic modules.
				snake_case__	:      Any     		=	DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
				create_dynamic_module(__lowerCAmelCase      )
				snake_case__	:      Dict     		=	Path(__lowerCAmelCase      ) / full_submodule
				if submodule == "local" or submodule == "git":
								# We always copy local files (we could hash the file to see if there was a change, and give them the name of
								# that hash, to only copy when there is a modification but it seems overkill for now).
								# The only reason we do the copy is to avoid putting too many folders in sys.path.
								shutil.copy(__lowerCAmelCase  ,  submodule_path / module_file      )
								for module_needed in modules_needed:
												snake_case__	:      List[Any]     		=	f"""{module_needed}.py"""
												shutil.copy(os.path.join(__lowerCAmelCase  ,  __lowerCAmelCase      )  ,  submodule_path / module_needed      )
				else:
								# Get the commit hash
								# TODO: we will get this info in the etag soon, so retrieve it from there and not here.
								if isinstance(__lowerCAmelCase  ,  __lowerCAmelCase      ):
												snake_case__	:      str     		=	use_auth_token
								elif use_auth_token is True:
												snake_case__	:      Tuple     		=	HfFolder.get_token()
								else:
												snake_case__	:      Dict     		=	None

								snake_case__	:      Optional[Any]     		=	model_info(__lowerCAmelCase  ,  revision=__lowerCAmelCase  ,  token=__lowerCAmelCase      ).sha

								# The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
								# benefit of versioning.
								snake_case__	:      int     		=	submodule_path / commit_hash
								snake_case__	:      str     		=	full_submodule + os.path.sep + commit_hash
								create_dynamic_module(__lowerCAmelCase      )

								if not (submodule_path / module_file).exists():
												shutil.copy(__lowerCAmelCase  ,  submodule_path / module_file      )
								# Make sure we also have every file with relative
								for module_needed in modules_needed:
												if not (submodule_path / module_needed).exists():
																get_cached_module_file(
																    __lowerCAmelCase  ,  f"""{module_needed}.py"""  ,  cache_dir=__lowerCAmelCase  ,  force_download=__lowerCAmelCase  ,  resume_download=__lowerCAmelCase  ,  proxies=__lowerCAmelCase  ,  use_auth_token=__lowerCAmelCase  ,  revision=__lowerCAmelCase  ,  local_files_only=__lowerCAmelCase  ,  )
				return os.path.join(__lowerCAmelCase  ,  __lowerCAmelCase      )





def 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = False  ,  __lowerCAmelCase = False  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = None  ,  __lowerCAmelCase = False  ,  **__lowerCAmelCase  ,  )   ->					Dict:


				"""simple docstring"""

				snake_case__	:      List[str]     		=	get_cached_module_file(
				    __lowerCAmelCase  ,  __lowerCAmelCase  ,  cache_dir=__lowerCAmelCase  ,  force_download=__lowerCAmelCase  ,  resume_download=__lowerCAmelCase  ,  proxies=__lowerCAmelCase  ,  use_auth_token=__lowerCAmelCase  ,  revision=__lowerCAmelCase  ,  local_files_only=__lowerCAmelCase  ,  )
				return get_class_in_module(__lowerCAmelCase  ,  final_module.replace('''.py'''  ,  ''''''      )      )






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


A__								=						datasets.logging.get_logger(__name__)


A__								=						'''\
@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",
}

'''

A__								=						'''\
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.
'''

A__								=						'''
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 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase=False  ,  __lowerCAmelCase=False  ,  __lowerCAmelCase=True  ,  __lowerCAmelCase=False  ,  __lowerCAmelCase="dummy_doc"      )   ->					int:


				"""simple docstring"""

				snake_case__	:      Dict     		=	{doc: key_lines}
				snake_case__	:      Any     		=	{doc: sys_lines}

				snake_case__	:      Dict     		=	{}

				snake_case__	:      List[str]     		=	0
				snake_case__	:      Optional[Any]     		=	0
				snake_case__	:      Optional[Any]     		=	0
				snake_case__	:      Dict     		=	0
				snake_case__	:      List[Any]     		=	0
				snake_case__	:      List[Any]     		=	0

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

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

				snake_case__		, snake_case__	:      int     		=	reader.get_doc_mentions(__lowerCAmelCase  ,  sys_doc_lines[doc]  ,  __lowerCAmelCase      )
				sys_singletons_num += singletons_num

				if NP_only or min_span:
								snake_case__	:      Union[str, Any]     		=	reader.set_annotated_parse_trees(__lowerCAmelCase  ,  key_doc_lines[doc]  ,  __lowerCAmelCase  ,  __lowerCAmelCase      )

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

								snake_case__		, snake_case__	:      Optional[int]     		=	reader.remove_nested_coref_mentions(__lowerCAmelCase  ,  __lowerCAmelCase      )
								sys_nested_coref_num += nested_mentions
								sys_removed_nested_clusters += removed_clusters

				snake_case__	:      Any     		=	reader.get_mention_assignments(__lowerCAmelCase  ,  __lowerCAmelCase      )
				snake_case__	:      Optional[int]     		=	reader.get_mention_assignments(__lowerCAmelCase  ,  __lowerCAmelCase      )

				snake_case__	:      List[Any]     		=	(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 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase      )   ->					str:


				"""simple docstring"""

				snake_case__	:      Optional[Any]     		=	get_coref_infos(__lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase      )

				snake_case__	:      str     		=	{}
				snake_case__	:      Optional[int]     		=	0
				snake_case__	:      List[Any]     		=	0

				for name, metric in metrics:
								snake_case__		, snake_case__		, snake_case__	:      Any     		=	evaluator.evaluate_documents(__lowerCAmelCase  ,  __lowerCAmelCase  ,  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:
								snake_case__	:      int     		=	(conll / 3) * 100
								logger.info(f"""CoNLL score: {conll:.2f}"""      )
								output_scores.update({'''conll_score''': conll}      )

				return output_scores



def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					List[str]:


				"""simple docstring"""

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





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



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

						if min_span:
										snake_case__	:      Optional[int]     		=	util.check_gold_parse_annotation(__lowercase  )
										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"

						snake_case__	:      Any     		=	evaluate(
						    key_lines=__lowercase   ,sys_lines=__lowercase   ,metrics=__lowercase   ,NP_only=__lowercase   ,remove_nested=__lowercase   ,keep_singletons=__lowercase   ,min_span=__lowercase   ,)

						return score

