






'''simple docstring'''
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_					=	'\\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'

a_					=	'\\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'

a_					=	'\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__			:  Any,		UpperCamelCase__			:  List[str],		UpperCamelCase__			:  Dict=False,		UpperCamelCase__			:  Optional[Any]=False,		UpperCamelCase__			:  Tuple=True,		UpperCamelCase__			:  List[Any]=False,		UpperCamelCase__			:  List[Any]="dummy_doc"							):




						'''simple docstring'''






						SCREAMING_SNAKE_CASE__       :			Dict													={doc: key_lines}
						SCREAMING_SNAKE_CASE__       :			List[Any]													={doc: sys_lines}

						SCREAMING_SNAKE_CASE__       :			Optional[Any]													={}

						SCREAMING_SNAKE_CASE__       :			Optional[int]													=0
						SCREAMING_SNAKE_CASE__       :			Optional[Any]													=0
						SCREAMING_SNAKE_CASE__       :			str													=0
						SCREAMING_SNAKE_CASE__       :			str													=0
						SCREAMING_SNAKE_CASE__       :			Any													=0
						SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=0

						SCREAMING_SNAKE_CASE__       :			Optional[Any]													=reader.get_doc_mentions(UpperCamelCase__,		key_doc_lines[doc],		UpperCamelCase__							)
						key_singletons_num += singletons_num

						if NP_only or min_span:
												SCREAMING_SNAKE_CASE__       :			List[str]													=reader.set_annotated_parse_trees(UpperCamelCase__,		key_doc_lines[doc],		UpperCamelCase__,		UpperCamelCase__							)

						SCREAMING_SNAKE_CASE__       :			Any													=reader.get_doc_mentions(UpperCamelCase__,		sys_doc_lines[doc],		UpperCamelCase__							)
						sys_singletons_num += singletons_num

						if NP_only or min_span:
												SCREAMING_SNAKE_CASE__       :			Optional[Any]													=reader.set_annotated_parse_trees(UpperCamelCase__,		key_doc_lines[doc],		UpperCamelCase__,		UpperCamelCase__							)

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

												SCREAMING_SNAKE_CASE__       :			Optional[Any]													=reader.remove_nested_coref_mentions(UpperCamelCase__,		UpperCamelCase__							)
												sys_nested_coref_num += nested_mentions
												sys_removed_nested_clusters += removed_clusters

						SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=reader.get_mention_assignments(UpperCamelCase__,		UpperCamelCase__							)
						SCREAMING_SNAKE_CASE__       :			List[str]													=reader.get_mention_assignments(UpperCamelCase__,		UpperCamelCase__							)

						SCREAMING_SNAKE_CASE__       :			List[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__			:  str,		UpperCamelCase__			:  Optional[int],		UpperCamelCase__			:  Tuple,		UpperCamelCase__			:  List[str],		UpperCamelCase__			:  Optional[int],		UpperCamelCase__			:  List[Any],		UpperCamelCase__			:  Optional[Any]							):




						'''simple docstring'''






						SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=get_coref_infos(UpperCamelCase__,		UpperCamelCase__,		UpperCamelCase__,		UpperCamelCase__,		UpperCamelCase__,		UpperCamelCase__							)

						SCREAMING_SNAKE_CASE__       :			int													={}
						SCREAMING_SNAKE_CASE__       :			Optional[Any]													=0
						SCREAMING_SNAKE_CASE__       :			Dict													=0

						for name, metric in metrics:
												SCREAMING_SNAKE_CASE__       :			Tuple													=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(1_0							),		f"Recall: {recall * 1_0_0:.2f}",		f" Precision: {precision * 1_0_0:.2f}",		f" F1: {fa * 1_0_0:.2f}",		)

						if conll_subparts_num == 3:
												SCREAMING_SNAKE_CASE__       :			List[str]													=(conll / 3) * 1_0_0
												logger.info(f"CoNLL score: {conll:.2f}"							)
												output_scores.update({'''conll_score''': conll}							)

						return output_scores





def 	_a(					UpperCamelCase__			:  List[str]							):




						'''simple docstring'''






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







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




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

							if min_span:
													SCREAMING_SNAKE_CASE__       :			Dict													=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"

							SCREAMING_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







'''simple docstring'''
import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


a_					=	get_logger(__name__)


a_					=	R'\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n'






class        __SCREAMING_SNAKE_CASE :




 @add_start_docstrings(__lowercase )
 def __call__( self		:							Any   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray )		->  jnp.ndarray:
       raise NotImplementedError(
           F"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )






class        __SCREAMING_SNAKE_CASE :




 @add_start_docstrings(__lowercase )
 def __call__( self		:							List[str]   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray )		->  jnp.ndarray:
       raise NotImplementedError(
           F"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 @add_start_docstrings(__lowercase )
 def __call__( self		:							Any   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int   , **__lowercase		:							List[str] )		->  jnp.ndarray:
       for processor in self:
             SCREAMING_SNAKE_CASE__       :			Optional[Any]													=inspect.signature(processor.__call__ ).parameters
             if len(__lowercase ) > 3:
                   if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ):
                         raise ValueError(
                             F"Make sure that all the required parameters: {list(function_args.keys() )} for "
                             F"{processor.__class__} are passed to the logits processor." )
                   SCREAMING_SNAKE_CASE__       :			List[Any]													=processor(__lowercase   , __lowercase   , __lowercase   , **__lowercase )
             else:
                   SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=processor(__lowercase   , __lowercase   , __lowercase )
       return scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							List[str]   , __lowercase		:							float )		->  Tuple:
       if not isinstance(__lowercase   , __lowercase ) or not (temperature > 0):
             raise ValueError(F"`temperature` has to be a strictly positive float, but is {temperature}" )

       SCREAMING_SNAKE_CASE__       :			Optional[int]													=temperature




 def __call__( self		:							Optional[int]   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int )		->  jnp.ndarray:
       SCREAMING_SNAKE_CASE__       :			int													=scores / self.temperature
       return scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							Tuple   , __lowercase		:							float   , __lowercase		:							float = -float('''Inf''' )   , __lowercase		:							int = 1 )		->  List[str]:
       if not isinstance(__lowercase   , __lowercase ) or (top_p < 0 or top_p > 1.0):
             raise ValueError(F"`top_p` has to be a float > 0 and < 1, but is {top_p}" )
       if not isinstance(__lowercase   , __lowercase ) or (min_tokens_to_keep < 1):
             raise ValueError(F"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}" )

       SCREAMING_SNAKE_CASE__       :			Tuple													=top_p
       SCREAMING_SNAKE_CASE__       :			List[str]													=filter_value
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=min_tokens_to_keep




 def __call__( self		:							int   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int )		->  jnp.ndarray:
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			List[Any]													=lax.top_k(__lowercase   , scores.shape[-1] )

       SCREAMING_SNAKE_CASE__       :			List[str]													=jnp.full_like(__lowercase   , self.filter_value )
       SCREAMING_SNAKE_CASE__       :			Tuple													=jax.nn.softmax(__lowercase   , axis=-1 ).cumsum(axis=-1 )
       SCREAMING_SNAKE_CASE__       :			Dict													=cumulative_probs < self.top_p

       # include the token that is higher than top_p as well
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=jnp.roll(__lowercase   , 1 )
       score_mask |= score_mask.at[:, 0].set(__lowercase )

       # min tokens to keep
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=score_mask.at[:, : self.min_tokens_to_keep].set(__lowercase )

       SCREAMING_SNAKE_CASE__       :			Dict													=jnp.where(__lowercase   , __lowercase   , __lowercase )
       SCREAMING_SNAKE_CASE__       :			int													=jax.lax.sort_key_val(__lowercase   , __lowercase )[-1]

       return next_scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							List[str]   , __lowercase		:							int   , __lowercase		:							float = -float('''Inf''' )   , __lowercase		:							int = 1 )		->  List[Any]:
       if not isinstance(__lowercase   , __lowercase ) or top_k <= 0:
             raise ValueError(F"`top_k` has to be a strictly positive integer, but is {top_k}" )

       SCREAMING_SNAKE_CASE__       :			str													=max(__lowercase   , __lowercase )
       SCREAMING_SNAKE_CASE__       :			List[Any]													=filter_value




 def __call__( self		:							List[Any]   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int )		->  jnp.ndarray:
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			Dict													=scores.shape
       SCREAMING_SNAKE_CASE__       :			str													=jnp.full(batch_size * vocab_size   , self.filter_value )

       SCREAMING_SNAKE_CASE__       :			List[Any]													=min(self.top_k   , scores.shape[-1] )  # Safety check
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			Optional[int]													=lax.top_k(__lowercase   , __lowercase )
       SCREAMING_SNAKE_CASE__       :			int													=jnp.broadcast_to((jnp.arange(__lowercase ) * vocab_size)[:, None]   , (batch_size, topk) ).flatten()
       SCREAMING_SNAKE_CASE__       :			str													=topk_scores.flatten()
       SCREAMING_SNAKE_CASE__       :			int													=topk_indices.flatten() + shift

       SCREAMING_SNAKE_CASE__       :			str													=next_scores_flat.at[topk_indices_flat].set(__lowercase )
       SCREAMING_SNAKE_CASE__       :			Any													=next_scores_flat.reshape(__lowercase   , __lowercase )
       return next_scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							Any   , __lowercase		:							int )		->  Optional[int]:
       SCREAMING_SNAKE_CASE__       :			List[str]													=bos_token_id




 def __call__( self		:							Tuple   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int )		->  jnp.ndarray:
       SCREAMING_SNAKE_CASE__       :			Tuple													=jnp.full(scores.shape   , -float('''inf''' ) )

       SCREAMING_SNAKE_CASE__       :			str													=1 - jnp.bool_(cur_len - 1 )

       SCREAMING_SNAKE_CASE__       :			Optional[int]													=jnp.where(__lowercase   , new_scores.at[:, self.bos_token_id].set(0 )   , __lowercase )

       return scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							Union[str, Any]   , __lowercase		:							int   , __lowercase		:							int )		->  List[str]:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=max_length
       SCREAMING_SNAKE_CASE__       :			int													=eos_token_id




 def __call__( self		:							Any   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int )		->  jnp.ndarray:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=jnp.full(scores.shape   , -float('''inf''' ) )

       SCREAMING_SNAKE_CASE__       :			str													=1 - jnp.bool_(cur_len - self.max_length + 1 )

       SCREAMING_SNAKE_CASE__       :			Optional[int]													=jnp.where(__lowercase   , new_scores.at[:, self.eos_token_id].set(0 )   , __lowercase )

       return scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							Union[str, Any]   , __lowercase		:							int   , __lowercase		:							int )		->  Tuple:
       if not isinstance(__lowercase   , __lowercase ) or min_length < 0:
             raise ValueError(F"`min_length` has to be a positive integer, but is {min_length}" )

       if not isinstance(__lowercase   , __lowercase ) or eos_token_id < 0:
             raise ValueError(F"`eos_token_id` has to be a positive integer, but is {eos_token_id}" )

       SCREAMING_SNAKE_CASE__       :			str													=min_length
       SCREAMING_SNAKE_CASE__       :			Tuple													=eos_token_id




 def __call__( self		:							Tuple   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int )		->  jnp.ndarray:
       # create boolean flag to decide if min length penalty should be applied
       SCREAMING_SNAKE_CASE__       :			List[str]													=1 - jnp.clip(cur_len - self.min_length   , 0   , 1 )

       SCREAMING_SNAKE_CASE__       :			Tuple													=jnp.where(__lowercase   , scores.at[:, self.eos_token_id].set(-float('''inf''' ) )   , __lowercase )

       return scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							int   , __lowercase		:							Optional[Any]   , __lowercase		:							Tuple )		->  List[str]:
       SCREAMING_SNAKE_CASE__       :			Dict													=list(__lowercase )
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=begin_index




 def __call__( self		:							Optional[Any]   , __lowercase		:							Optional[Any]   , __lowercase		:							Dict   , __lowercase		:							int )		->  List[str]:
       SCREAMING_SNAKE_CASE__       :			Any													=1 - jnp.bool_(cur_len - self.begin_index )

       SCREAMING_SNAKE_CASE__       :			Optional[int]													=jnp.where(__lowercase   , scores.at[:, self.begin_suppress_tokens].set(-float('''inf''' ) )   , __lowercase )

       return scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							Optional[Any]   , __lowercase		:							list )		->  Dict:
       SCREAMING_SNAKE_CASE__       :			int													=list(__lowercase )




 def __call__( self		:							str   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int )		->  jnp.ndarray:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=scores.at[..., self.suppress_tokens].set(-float('''inf''' ) )

       return scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							List[Any]   , __lowercase		:							List[str] )		->  Optional[Any]:
       SCREAMING_SNAKE_CASE__       :			List[str]													=dict(__lowercase )
       # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
       # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
       # Indexes without forced tokens will have a negative value.
       SCREAMING_SNAKE_CASE__       :			Any													=jnp.ones((max(force_token_map.keys() ) + 1)   , dtype=jnp.intaa ) * -1
       for index, token in force_token_map.items():
             if token is not None:
                   SCREAMING_SNAKE_CASE__       :			Tuple													=force_token_array.at[index].set(__lowercase )
       SCREAMING_SNAKE_CASE__       :			Dict													=jnp.intaa(__lowercase )




 def __call__( self		:							Optional[Any]   , __lowercase		:							jnp.ndarray   , __lowercase		:							jnp.ndarray   , __lowercase		:							int )		->  jnp.ndarray:
       def _force_token(__lowercase		:							Union[str, Any] ):
             SCREAMING_SNAKE_CASE__       :			Dict													=scores.shape[0]
             SCREAMING_SNAKE_CASE__       :			Optional[int]													=self.force_token_array[generation_idx]

             SCREAMING_SNAKE_CASE__       :			Optional[int]													=jnp.ones_like(__lowercase   , dtype=scores.dtype ) * -float('''inf''' )
             SCREAMING_SNAKE_CASE__       :			Tuple													=jnp.zeros((batch_size, 1)   , dtype=scores.dtype )
             SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=lax.dynamic_update_slice(__lowercase   , __lowercase   , (0, current_token) )
             return new_scores

       SCREAMING_SNAKE_CASE__       :			Tuple													=lax.cond(
           cur_len >= self.force_token_array.shape[0]   , lambda: scores   , lambda: lax.cond(
               self.force_token_array[cur_len] >= 0   , lambda: _force_token(__lowercase )   , lambda: scores   , )   , )
       return scores






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							List[str]   , __lowercase		:							List[Any]   , __lowercase		:							List[str]   , __lowercase		:							Any )		->  Tuple:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=generate_config.eos_token_id
       SCREAMING_SNAKE_CASE__       :			List[Any]													=generate_config.no_timestamps_token_id
       SCREAMING_SNAKE_CASE__       :			List[Any]													=generate_config.no_timestamps_token_id + 1

       SCREAMING_SNAKE_CASE__       :			Dict													=decoder_input_length + 1

       if generate_config.is_multilingual:
             # room for language token and task token
             self.begin_index += 2
       if hasattr(__lowercase   , '''max_initial_timestamp_index''' ):
             SCREAMING_SNAKE_CASE__       :			int													=generate_config.max_initial_timestamp_index
       else:
             SCREAMING_SNAKE_CASE__       :			Optional[int]													=model_config.vocab_size
       if self.max_initial_timestamp_index is None:
             SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=model_config.vocab_size




 def __call__( self		:							List[Any]   , __lowercase		:							Union[str, Any]   , __lowercase		:							Any   , __lowercase		:							str )		->  Optional[Any]:
       # suppress <|notimestamps|> which is handled by without_timestamps
       SCREAMING_SNAKE_CASE__       :			Any													=scores.at[:, self.no_timestamps_token_id].set(-float('''inf''' ) )

       def handle_pairs(__lowercase		:							Any   , __lowercase		:							Optional[int] ):
             SCREAMING_SNAKE_CASE__       :			Optional[int]													=jnp.where((cur_len - self.begin_index) >= 1   , __lowercase   , __lowercase )
             SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=jnp.where(
                 input_ids_k[cur_len - 1] >= self.timestamp_begin   , True and last_was_timestamp   , __lowercase   , )

             SCREAMING_SNAKE_CASE__       :			List[str]													=jnp.where((cur_len - self.begin_index) < 2   , __lowercase   , __lowercase )
             SCREAMING_SNAKE_CASE__       :			Any													=jnp.where(
                 input_ids_k[cur_len - 2] >= self.timestamp_begin   , __lowercase   , __lowercase   , )

             return jnp.where(
                 __lowercase   , jnp.where(
                     penultimate_was_timestamp > 0   , scores_k.at[self.timestamp_begin :].set(-float('''inf''' ) )   , scores_k.at[: self.eos_token_id].set(-float('''inf''' ) )   , )   , __lowercase   , )

       SCREAMING_SNAKE_CASE__       :			List[str]													=jax.vmap(__lowercase )(__lowercase   , __lowercase )

       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=jnp.where(cur_len == self.begin_index   , __lowercase   , __lowercase )
       SCREAMING_SNAKE_CASE__       :			int													=jnp.where(
           self.max_initial_timestamp_index is not None   , True and apply_max_initial_timestamp   , __lowercase   , )

       SCREAMING_SNAKE_CASE__       :			Optional[int]													=self.timestamp_begin + self.max_initial_timestamp_index

       SCREAMING_SNAKE_CASE__       :			int													=jnp.where(
           __lowercase   , scores.at[:, last_allowed + 1 :].set(-float('''inf''' ) )   , __lowercase   , )

       # if sum of probability over timestamps is above any other token, sample timestamp
       SCREAMING_SNAKE_CASE__       :			Any													=jax.nn.log_softmax(__lowercase   , axis=-1 )

       def handle_cumulative_probs(__lowercase		:							Optional[int]   , __lowercase		:							str ):
             SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]   , axis=-1 )
             SCREAMING_SNAKE_CASE__       :			List[Any]													=jnp.max(logprobs_k[: self.timestamp_begin] )
             return jnp.where(
                 timestamp_logprob > max_text_token_logprob   , scores_k.at[: self.timestamp_begin].set(-float('''inf''' ) )   , __lowercase   , )

       SCREAMING_SNAKE_CASE__       :			Any													=jax.vmap(__lowercase )(__lowercase   , __lowercase )

       return scores