



import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
 import tensorflow as tf

 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

lowercase_:  Optional[int]     						=					logging.get_logger(__name__)



class 						lowercase__      (enum.Enum						):

     """simple docstring"""






     __UpperCamelCase    :	List[str]		=       0
     __UpperCamelCase    :	List[Any]		=       1



@add_end_docstrings(__lowercase						)
class 						lowercase__      (__lowercase						):

     """simple docstring"""






     __UpperCamelCase    :	str		=       '''generated'''


     def __init__( self :	Any   ,			*__a :	Optional[int]   ,			**__a :	Any ):
      super().__init__(*__a   ,			**__a )

      self.check_model_type(
          TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
          if self.framework == """tf"""
          else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING )


     def 		lowercase   ( self :	List[str]   ,			__a :	List[str]=None   ,			__a :	Tuple=None   ,			__a :	Tuple=None   ,			__a :	Any=None   ,			__a :	int=None   ,			__a :	Any=None   ,			**__a :	str   ,			):
      snake_case__				:							Any      							= {}
      if truncation is not None:
       snake_case__				:							List[str]      							= truncation

      snake_case__				:							Optional[Any]      							= generate_kwargs

      snake_case__				:							Dict      							= {}
      if return_tensors is not None and return_type is None:
       snake_case__				:							int      							= ReturnType.TENSORS if return_tensors else ReturnType.TEXT
      if return_type is not None:
       snake_case__				:							Any      							= return_type

      if clean_up_tokenization_spaces is not None:
       snake_case__				:							Optional[int]      							= clean_up_tokenization_spaces

      if stop_sequence is not None:
       snake_case__				:							Tuple      							= self.tokenizer.encode(__a   ,			add_special_tokens=__a )
       if len(__a ) > 1:
        warnings.warn(
            """Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
            """ the stop sequence will be used as the stop sequence string in the interim.""" )
       snake_case__				:							Optional[int]      							= stop_sequence_ids[0]

      return preprocess_params, forward_params, postprocess_params


     def 		lowercase   ( self :	List[Any]   ,			__a :	int   ,			__a :	int   ,			__a :	int ):
      return True


     def 		lowercase   ( self :	List[Any]   ,			*__a :	Union[str, Any]   ,			__a :	Optional[int] ):
      snake_case__				:							List[str]      							= self.model.config.prefix if self.model.config.prefix is not None else """"""
      if isinstance(args[0]   ,			__a ):
       if self.tokenizer.pad_token_id is None:
        raise ValueError("""Please make sure that the tokenizer has a pad_token_id when using a batch input""" )
       snake_case__				:							List[str]      							= ([prefix + arg for arg in args[0]],)
       snake_case__				:							Dict      							= True

      elif isinstance(args[0]   ,			__a ):
       snake_case__				:							List[str]      							= (prefix + args[0],)
       snake_case__				:							Union[str, Any]      							= False
      else:
       raise ValueError(
           f' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`' )
      snake_case__				:							Dict      							= self.tokenizer(*__a   ,			padding=__a   ,			truncation=__a   ,			return_tensors=self.framework )
      # This is produced by tokenizers but is an invalid generate kwargs
      if "token_type_ids" in inputs:
       del inputs["token_type_ids"]
      return inputs


     def __call__( self :	Any   ,			*__a :	Optional[int]   ,			**__a :	Dict ):
      snake_case__				:							List[Any]      							= super().__call__(*__a   ,			**__a )
      if (
          isinstance(args[0]   ,			__a )
          and all(isinstance(__a   ,			__a ) for el in args[0] )
          and all(len(__a ) == 1 for res in result )
      ):
       return [res[0] for res in result]
      return result


     def 		lowercase   ( self :	Optional[int]   ,			__a :	Optional[Any]   ,			__a :	str=TruncationStrategy.DO_NOT_TRUNCATE   ,			**__a :	str ):
      snake_case__				:							Dict      							= self._parse_and_tokenize(__a   ,			truncation=__a   ,			**__a )
      return inputs


     def 		lowercase   ( self :	Optional[Any]   ,			__a :	Any   ,			**__a :	List[str] ):

      if self.framework == "pt":
       snake_case__				:							str      							= model_inputs["""input_ids"""].shape
      elif self.framework == "tf":
       snake_case__				:							Optional[int]      							= tf.shape(model_inputs["""input_ids"""] ).numpy()

      snake_case__				:							List[str]      							= generate_kwargs.get("""min_length"""   ,			self.model.config.min_length )
      snake_case__				:							Optional[Any]      							= generate_kwargs.get("""max_length"""   ,			self.model.config.max_length )
      self.check_inputs(__a   ,			generate_kwargs["""min_length"""]   ,			generate_kwargs["""max_length"""] )
      snake_case__				:							Union[str, Any]      							= self.model.generate(**__a   ,			**__a )
      snake_case__				:							Optional[int]      							= output_ids.shape[0]
      if self.framework == "pt":
       snake_case__				:							Union[str, Any]      							= output_ids.reshape(__a   ,			out_b // in_b   ,			*output_ids.shape[1:] )
      elif self.framework == "tf":
       snake_case__				:							Tuple      							= tf.reshape(__a   ,			(in_b, out_b // in_b, *output_ids.shape[1:]) )
      return {"output_ids": output_ids}


     def 		lowercase   ( self :	str   ,			__a :	Union[str, Any]   ,			__a :	Any=ReturnType.TEXT   ,			__a :	Dict=False ):
      snake_case__				:							Union[str, Any]      							= []
      for output_ids in model_outputs["output_ids"][0]:
       if return_type == ReturnType.TENSORS:
        snake_case__				:							Optional[int]      							= {f'{self.return_name}_token_ids': output_ids}
       elif return_type == ReturnType.TEXT:
        snake_case__				:							Optional[int]      							= {
            f'{self.return_name}_text': self.tokenizer.decode(
                __a   ,			skip_special_tokens=__a   ,			clean_up_tokenization_spaces=__a   ,			)
        }
       records.append(__a )
      return records



@add_end_docstrings(__lowercase						)
class 						lowercase__      (__lowercase						):

     """simple docstring"""






     __UpperCamelCase    :	Optional[int]		=       '''summary'''


     def __call__( self :	Tuple   ,			*__a :	Any   ,			**__a :	str ):
      return super().__call__(*__a   ,			**__a )


     def 		lowercase   ( self :	int   ,			__a :	int   ,			__a :	int   ,			__a :	int ):

      if max_length < min_length:
       logger.warning(f'Your min_length={min_length} must be inferior than your max_length={max_length}.' )

      if input_length < max_length:
       logger.warning(
           f'Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '
           """a summarization task, where outputs shorter than the input are typically wanted, you might """
           f'consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})' )



@add_end_docstrings(__lowercase						)
class 						lowercase__      (__lowercase						):

     """simple docstring"""






     __UpperCamelCase    :	Union[str, Any]		=       '''translation'''


     def 		lowercase   ( self :	Union[str, Any]   ,			__a :	int   ,			__a :	int   ,			__a :	int ):

      if input_length > 0.9 * max_length:
       logger.warning(
           f'Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '
           """increasing your max_length manually, e.g. translator('...', max_length=400)""" )
      return True


     def 		lowercase   ( self :	Optional[Any]   ,			*__a :	Dict   ,			__a :	List[Any]=TruncationStrategy.DO_NOT_TRUNCATE   ,			__a :	Any=None   ,			__a :	List[Any]=None ):

      if getattr(self.tokenizer   ,			"""_build_translation_inputs"""   ,			__a ):
       return self.tokenizer._build_translation_inputs(
           *__a   ,			return_tensors=self.framework   ,			truncation=__a   ,			src_lang=__a   ,			tgt_lang=__a )
      else:
       return super()._parse_and_tokenize(*__a   ,			truncation=__a )


     def 		lowercase   ( self :	List[Any]   ,			__a :	Any=None   ,			__a :	Union[str, Any]=None   ,			**__a :	Union[str, Any] ):
      snake_case__				:							List[Any]      							= super()._sanitize_parameters(**__a )
      if src_lang is not None:
       snake_case__				:							int      							= src_lang
      if tgt_lang is not None:
       snake_case__				:							Any      							= tgt_lang
      if src_lang is None and tgt_lang is None:
       # Backward compatibility, direct arguments use is preferred.
       snake_case__				:							Tuple      							= kwargs.get("""task"""   ,			self.task )
       snake_case__				:							Union[str, Any]      							= task.split("""_""" )
       if task and len(__a ) == 4:
        # translation, XX, to YY
        snake_case__				:							List[Any]      							= items[1]
        snake_case__				:							str      							= items[3]
      return preprocess_params, forward_params, postprocess_params


     def __call__( self :	List[Any]   ,			*__a :	int   ,			**__a :	Union[str, Any] ):
      return super().__call__(*__a   ,			**__a )











'''simple docstring'''






from sklearn.metrics import recall_score

import datasets


__UpperCamelCase					    =	"\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n"


__UpperCamelCase					    =	"\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {'recall': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {'recall': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {'recall': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'recall': array([1., 0., 0.])}\n"


__UpperCamelCase					    =	"\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n"




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

		def 	lowercase__     (   self					:   Optional[int]			)					->    Any:


					"""simple docstring"""

					return datasets.MetricInfo(
					    description=_DESCRIPTION  ,      citation=_CITATION  ,      inputs_description=_KWARGS_DESCRIPTION  ,      features=datasets.Features(
					        {
					            """predictions""": datasets.Sequence(datasets.Value("""int32"""			)			),
					            """references""": datasets.Sequence(datasets.Value("""int32"""			)			),
					        }
					        if self.config_name == """multilabel"""
					        else {
					            """predictions""": datasets.Value("""int32"""			),
					            """references""": datasets.Value("""int32"""			),
					        }			)  ,      reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""]  ,      )

		def 	lowercase__     (   self					:   Tuple  ,      __magic_name__					:   int  ,      __magic_name__					:   Union[str, Any]  ,      __magic_name__					:   Any=None  ,      __magic_name__					:   Optional[Any]=1  ,      __magic_name__					:   List[str]="binary"  ,      __magic_name__					:   Tuple=None  ,      __magic_name__					:   Dict="warn"  ,      )					->    Any:


					"""simple docstring"""

					__snake_case					:      Tuple							      =     recall_score(
					    __magic_name__  ,      __magic_name__  ,      labels=__magic_name__  ,      pos_label=__magic_name__  ,      average=__magic_name__  ,      sample_weight=__magic_name__  ,      zero_division=__magic_name__  ,      )
					return {"recall": float(__magic_name__			) if score.size == 1 else score}


